Source file clang.ml

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
[%%metapackage "metapp"]
[%%metadir "config/.clangml_config.objs/byte"]

module type S = Ast_sig.S

[%%metadef
let node_module s = Ppxlib.Ast_helper.Mod.structure [%str
  module Self = struct
    [%%meta Metapp.Stri.of_list s]

    let compare = Refl.compare [%refl: t] []

    let equal = Refl.equal [%refl: t] []

    let hash = Refl.hash [%refl: t] []

    let pp = Refl.pp [%refl: t] []

    let show = Refl.show [%refl: t] []
  end

  include Self

  module Set = Set.Make (Self)

  module Map = Map.Make (Self)

  module Hashtbl = Hashtbl.Make (Self)
]]

module Bindings = struct
  include Clang__bindings

  include Special_bindings
end

include Bindings

external compare_cursors :
  cxcursor -> cxcursor -> int = "clang_ext_compare_cursor_boxed"

module Cursor = struct
  module Self = struct
    type t = cxcursor

    let compare = compare_cursors

    let equal = equal_cursors

    let hash = hash_cursor
  end

  include Self

  module Hashtbl = Hashtbl.Make (Self)

  module Set = Set.Make (Self)

  module Map = Map.Make (Self)
end

module Types = Clang__types

include Types

include Clang__utils

module Standard = Standard

module Command_line = Clang__command_line

let version () =
  ext_get_version ()

let make_include_dir path =
  List.fold_left Filename.concat Clangml_config.includedir path

let includedir =
  make_include_dir
    [Filename.parent_dir_name; "lib"; "clang"; Clangml_config.version_string;
     "include"]

let default_include_directories () =
  (*let cpp_lib = make_include_dir ["c++"; "v1"] in*)
  let macos_sdk =
    "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/" in
  let gentoo_dir =
    "/usr/lib/clang/" ^ Clangml_config.version_string ^ "/include/" in
  let centos_dir =
    "/usr/lib64/clang/" ^ Clangml_config.version_string ^ "/include/" in
  [macos_sdk; (*cpp_lib;*) includedir; gentoo_dir; centos_dir]

let rec filter_out_prefix_from_list p list =
  match list with
  | hd :: tl when p hd -> filter_out_prefix_from_list p tl
  | _ -> list

(*
let string_chop_prefix_opt prefix s =
  let prefix_length = String.length prefix in
  let length = String.length s in
  if prefix_length <= length then
    if String.sub s 0 prefix_length = prefix then
      Some (String.sub s prefix_length (length - prefix_length))
    else
      None
  else
    None
*)

let rec get_typedef_underlying_type ?(recursive = false) (t : cxtype) =
  if get_type_kind t = Typedef then
    let result = get_typedef_decl_underlying_type (get_type_declaration t) in
    if recursive then
      get_typedef_underlying_type ~recursive:true result
    else
      result
  else
    t

let rec get_typedef_underlying_type_loc ?(recursive = false)
    (t : clang_ext_typeloc) =
  if ext_type_loc_get_class t = Typedef then
    let result =
      ext_typedef_decl_get_underlying_type_loc
        (get_type_declaration (ext_type_loc_get_type t)) in
    if recursive then
      get_typedef_underlying_type_loc ~recursive:true result
    else
      result
  else
    t

module Init_list = struct
  let syntactic_form cursor =
    let result = ext_init_list_expr_get_syntactic_form cursor in
    match get_cursor_kind result with
    | InvalidCode -> cursor
    | _ -> result

  let semantic_form cursor =
    let result = ext_init_list_expr_get_semantic_form cursor in
    match get_cursor_kind result with
    | InvalidCode -> cursor
    | _ -> result

  let get_form (form : Clang__ast_options.init_list_form) cursor =
    match form with
    | Syntactic -> syntactic_form cursor
    | Semantic -> semantic_form cursor
end

module Custom (Node : Clang__ast.NodeS) = struct
module Printer = Printer.Make (Node)

[%%meta Metapp.Stri.of_list ((new Metapp.filter)#structure [%str
module Ast = struct
  include Clang__ast.Common

  include Clang__ast.Custom (Node)

  let node ?decoration ?cursor ?location ?qual_type desc =
    let decoration : decoration =
      match decoration, cursor, location, qual_type with
      | Some decoration, None, None, None -> decoration
      | None, Some cursor, None, None -> Cursor cursor
      | None, None, location, qual_type -> Custom { location; qual_type }
      | _ -> invalid_arg "node" in
    { decoration; desc }

  let var
      ?(linkage = NoLinkage) ?var_init ?(constexpr = false)
      ?(attributes = []) var_name var_type =
    { linkage; var_name; var_type; var_init; constexpr; attributes }

  let function_decl
      ?(linkage = NoLinkage) ?body ?(deleted = false) ?(constexpr = false)
      ?(inline_specified = false) ?(inlined = false) ?nested_name_specifier
      ?(attributes = []) ?(has_written_prototype = false)
      function_type name =
    { linkage; body; deleted; constexpr; inline_specified; inlined;
      function_type; nested_name_specifier; name; attributes;
      has_written_prototype }

  let function_type ?(calling_conv = (C : cxcallingconv)) ?parameters
        ?exception_spec ?(ref_qualifier = (None : cxrefqualifierkind)) result =
    { calling_conv; parameters; result; exception_spec; ref_qualifier }

  let parameters ?(variadic = false) non_variadic =
    { variadic; non_variadic }

  let parameter ?default qual_type name =
    { default; qual_type; name }

  let ident_ref ?nested_name_specifier ?(template_arguments = [])
      name : ident_ref =
    { nested_name_specifier; name; template_arguments }

  let identifier_name ?nested_name_specifier ?template_arguments name =
    ident_ref ?nested_name_specifier ?template_arguments (IdentifierName name)

  let constant_array ?size_as_expr element size =
    ConstantArray { element; size; size_as_expr }

  let if_ ?init ?condition_variable ?else_branch cond then_branch =
    If { init; condition_variable; cond; then_branch; else_branch }

  let new_instance ?(placement_args = []) ?array_size ?init ?args qual_type =
    let init =
      match init, args with
      | Some _, Some _ ->
          invalid_arg
          "Clang.Ast.new_instance: ~init and ~args are mutually exclusive"
      | init, None -> init
      | None, Some args ->
          Some (node (Node.from_val (Construct { qual_type; args; }))) in
    New { placement_args; qual_type; array_size; init }

  let delete ?(global_delete = false) ?(array_form = false) argument =
    Delete { global_delete; array_form; argument }

  let enum_decl ?(complete_definition = true) ?(attributes = []) name
      constants =
    EnumDecl { name; constants; complete_definition; attributes }

  let cursor_of_decoration decoration =
    match decoration with
    | Cursor cursor -> cursor
    | Custom _ -> get_null_cursor ()

  let cursor_of_node node =
    cursor_of_decoration node.decoration

  let location_of_decoration decoration =
    match decoration with
    | Cursor cursor -> Clang (get_cursor_location cursor)
    | Custom { location; _ } ->
        match location with
        | Some location -> location
        | None -> Clang (get_cursor_location (get_null_cursor ()))

  let location_of_node node =
    location_of_decoration node.decoration

  let tokens_of_node node =
    let cursor = cursor_of_node node in
    let tu = cursor_get_translation_unit cursor in
    Array.map (get_token_spelling tu) (tokenize tu (get_cursor_extent cursor))

  include Clang__ast_utils

  module Options = Clang__ast_options

  module type OptionsS = sig
    val options : Options.t
  end

  let attribute_of_cxtype cxtype =
    let attribute_desc : attribute_desc =
      Other (ext_attributed_type_get_attr_kind cxtype) in
    node (Node.from_val attribute_desc)

  module Converter (Options : OptionsS) = struct
    let options = Options.options

    exception Invalid_structure

    (* Hack for having current function declaration to provide function name
       for predefined identifiers on Clang 3.4 and Clang 3.5. *)
    let current_decl = ref (get_null_cursor ())

    let is_not_ref cursor =
      match get_cursor_kind cursor with
      | TypeRef | NamespaceRef | ParmDecl -> false
      | _ -> true

    let make_integer_literal (i : cxint) (ty : cxtypekind) =
      match
        if options.convert_integer_literals then
          int_of_cxint_opt ~signed:(is_signed_integer ty) i
        else
          None
      with
      | None -> CXInt i
      | Some i -> Int i

    let is_template_parameter cursor =
      match get_cursor_kind cursor with
      | TemplateTypeParameter
      | NonTypeTemplateParameter
      | TemplateTemplateParameter -> true
      | _ -> false

    let rec convert_nested_name_specifier
        (name : clang_ext_nestednamespecifier)
        : nested_name_specifier option =
      let rec enumerate accu name =
        let component = convert_nested_name_specifier_component name in
        match component with
        | Some component ->
            let name = ext_nested_name_specifier_get_prefix name in
            enumerate (component :: accu) name
        | None -> accu in
      match ext_nested_name_specifier_get_kind name with
      | InvalidNestedNameSpecifier -> None
      | _ -> Some (enumerate [] name)

    and convert_nested_name_specifier_component
        (name : clang_ext_nestednamespecifier) =
      match ext_nested_name_specifier_get_kind name with
      | Identifier ->
          let ident =
            ext_nested_name_specifier_get_as_identifier name in
          Some (NestedIdentifier ident)
      | Namespace ->
          let decl = ext_nested_name_specifier_get_as_namespace name in
          Some (NamespaceName (get_cursor_spelling decl))
      | NamespaceAlias ->
          let decl = ext_nested_name_specifier_get_as_namespace name in
          Some (NamespaceAliasName (get_cursor_spelling decl))
      | TypeSpec ->
          let ty = ext_nested_name_specifier_get_as_type name in
          Some (TypeSpec (ty |> of_cxtype))
      | TypeSpecWithTemplate ->
          let ty = ext_nested_name_specifier_get_as_type name in
          Some (TypeSpecWithTemplate (ty |> of_cxtype))
      | Global -> Some Global
      | InvalidNestedNameSpecifier -> None
      | Super -> raise Invalid_structure

    and convert_nested_name_specifier_loc
        (name : clang_ext_nestednamespecifierloc)
        : nested_name_specifier option =
      let rec enumerate accu name =
        let ns = ext_nested_name_specifier_loc_get_nested_name_specifier name in
        let component =
          match ext_nested_name_specifier_get_kind ns with
          | TypeSpec ->
              let ty = ext_nested_name_specifier_loc_get_as_type_loc name in
              Some (TypeSpec (ty |> of_type_loc))
          | TypeSpecWithTemplate ->
              let ty = ext_nested_name_specifier_loc_get_as_type_loc name in
              Some (TypeSpecWithTemplate (ty |> of_type_loc))
          | _ -> convert_nested_name_specifier_component ns in
        match component with
        | None -> accu
        | Some component ->
            let name = ext_nested_name_specifier_loc_get_prefix name in
            enumerate (component :: accu) name in
      match ext_nested_name_specifier_get_kind
          (ext_nested_name_specifier_loc_get_nested_name_specifier name) with
      | InvalidNestedNameSpecifier -> None
      | _ -> Some (enumerate [] name)

    and declaration_name_of_cxcursor cursor =
      let name = ext_decl_get_name cursor in
      convert_declaration_name name

    and convert_declaration_name name =
      match ext_declaration_name_get_kind name with
      | Identifier ->
          IdentifierName (ext_declaration_name_get_as_identifier name)
      | CXXConstructorName ->
          ConstructorName
            (ext_declaration_name_get_cxxname_type name |> of_cxtype)
      | CXXDestructorName ->
          DestructorName
            (ext_declaration_name_get_cxxname_type name |> of_cxtype)
      | CXXConversionFunctionName ->
          ConversionFunctionName
            (ext_declaration_name_get_cxxname_type name |> of_cxtype)
      | CXXDeductionGuideName ->
          DeductionGuideName
            (ext_declaration_name_get_cxxdeduction_guide_template name |>
             decl_of_cxcursor)
      | CXXOperatorName ->
          OperatorName (ext_declaration_name_get_cxxoverloaded_operator name)
      | CXXLiteralOperatorName ->
          LiteralOperatorName
            (ext_declaration_name_get_cxxliteral_identifier name)
      | _ -> raise Invalid_structure

    and ident_ref_of_cxcursor cursor =
      let nested_name_specifier =
        cursor |> ext_decl_get_nested_name_specifier_loc |>
        convert_nested_name_specifier_loc in
      let name = declaration_name_of_cxcursor cursor in
      let template_arguments = extract_template_arguments cursor in
      { nested_name_specifier; name; template_arguments }

    and make_template_name name =
      match ext_template_name_get_kind name with
      | Template ->
          NameTemplate (
            ext_template_name_get_as_template_decl name |> get_cursor_spelling)
      | OverloadedTemplate -> OverloadedTemplate
      | QualifiedTemplate -> QualifiedTemplate
      | DependentTemplate -> DependentTemplate
      | SubstTemplateTemplateParm -> SubstTemplateTemplateParm
      | SubstTemplateTemplateParmPack -> SubstTemplateTemplateParmPack
      | InvalidNameKind -> InvalidNameKind

    and make_template_argument argument : template_argument =
      match ext_template_argument_get_kind argument with
      | Type ->
          Type (
            ext_template_argument_get_as_type argument |>
            of_cxtype)
      | Declaration ->
          ArgumentDecl (
            decl_of_cxcursor
              (ext_template_argument_get_as_decl argument))
      | NullPtr ->
          NullPtr (
            ext_template_argument_get_null_ptr_type argument |>
            of_cxtype)
      | Integral ->
          let qual_type =
            of_cxtype (ext_template_argument_get_integral_type argument) in
          Integral {
            value =
              make_integer_literal
                (ext_template_argument_get_as_integral argument)
                (get_type_kind qual_type.cxtype);
            qual_type }
      | Template ->
          TemplateTemplateArgument (
            ext_template_argument_get_as_template_or_template_pattern
              argument |>
            make_template_name)
      | TemplateExpansion ->
          TemplateExpansion (
            ext_template_argument_get_as_template_or_template_pattern
              argument |>
            make_template_name)
      | Expression ->
          ExprTemplateArgument (
            ext_template_argument_get_as_expr argument |>
            expr_of_cxcursor)
      | Pack ->
          Pack (
              List.init
                (ext_template_argument_get_pack_size argument)
                begin fun i ->
                  ext_template_argument_get_pack_argument argument i |>
                  make_template_argument
                end
          )
      | _ -> raise Invalid_structure

    and of_type_loc (type_loc : clang_ext_typeloc) =
      let unqualify type_loc =
        match ext_type_loc_get_class type_loc with
        | Qualified -> ext_qualified_type_loc_get_unqualified_loc type_loc
        | _ -> type_loc in
      let cxtype = ext_type_loc_get_type type_loc in
      let type_loc = unqualify type_loc in
      let make_qual_type cxtype type_loc desc =
        { cxtype; type_loc = Some type_loc; desc;
          const = is_const_qualified_type cxtype;
          volatile = is_volatile_qualified_type cxtype;
          restrict = is_restrict_qualified_type cxtype; } in
      let make_paren, type_loc, cxtype =
        match ext_type_loc_get_class type_loc with
        | Paren ->
            let type_loc' = ext_paren_type_loc_get_inner_loc type_loc in
            let cxtype' = ext_type_loc_get_type type_loc' in
            let type_loc' = unqualify type_loc' in
            let make_paren ty =
              if options.ignore_paren_in_types then
                ty
              else
                make_qual_type cxtype type_loc
                  (Node.from_val (ParenType ty)) in
            make_paren, type_loc', cxtype'
        | _ -> Fun.id, type_loc, cxtype in
      let desc () =
        match ext_type_loc_get_class type_loc with
        | Attributed ->
            let attribute =
              if Clangml_config.version.major >= 8 then
                ext_attributed_type_loc_get_attr type_loc |>
                attribute_of_cxcursor
              else
                attribute_of_cxtype cxtype in
            Attributed {
              modified_type =
                ext_attributed_type_loc_get_modified_loc type_loc |>
                of_type_loc;
              attribute
            }
        |_ ->
        match get_type_kind cxtype with
        | Invalid -> InvalidType
        | ConstantArray ->
            let size = cxtype |> get_array_size in
            let element =
              ext_array_type_loc_get_element_loc type_loc |> of_type_loc in
            let size_as_expr =
              ext_array_type_loc_get_size_expr type_loc |>
              expr_of_cxcursor in
            constant_array element size ~size_as_expr
        | Vector ->
            let element = cxtype |> get_element_type |> of_cxtype in
            let size = cxtype |> get_num_elements in
            Vector { element; size }
        | IncompleteArray ->
            let element =
              ext_array_type_loc_get_element_loc type_loc |> of_type_loc in
            IncompleteArray element
        | VariableArray ->
            let element =
              ext_array_type_loc_get_element_loc type_loc |> of_type_loc in
            let size =
              cxtype |> ext_variable_array_type_get_size_expr |>
              expr_of_cxcursor in
            VariableArray { element; size }
        | Pointer ->
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc type_loc |>
              of_type_loc in
            Pointer pointee
        | LValueReference ->
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc type_loc |>
              of_type_loc in
            LValueReference pointee
        | RValueReference ->
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc type_loc |>
              of_type_loc in
            RValueReference pointee
        | Enum ->
            Enum (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | Record ->
            Record (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | Typedef ->
            Typedef (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | FunctionProto
        | FunctionNoProto ->
            let function_type =
              type_loc |>
              function_type_of_type_loc (parameters_of_type_loc type_loc) in
            FunctionType function_type
        | Complex ->
            let element_type = cxtype |> get_element_type |> of_cxtype in
            Complex element_type
        | MemberPointer ->
            let class_ =
              ext_member_pointer_type_loc_get_class_loc type_loc |>
              of_type_loc in
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc type_loc |>
              of_type_loc in
            MemberPointer { pointee; class_ }
        | _ ->
            begin
              match ext_type_get_kind cxtype with
              | Elaborated -> (* Here for Clang <3.9.0 *)
                  let nested_name_specifier =
                    ext_type_loc_get_qualifier_loc type_loc |>
                    convert_nested_name_specifier_loc in
                  Elaborated {
                    keyword = ext_elaborated_type_get_keyword cxtype;
                    nested_name_specifier;
                    named_type =
                      ext_elaborated_type_loc_get_named_type_loc type_loc |>
                      of_type_loc
                  }
              | PackExpansion ->
                  let pattern =
                    ext_pack_expansion_type_loc_get_pattern_loc type_loc |>
                    of_type_loc in
                  PackExpansion pattern
              | TypeOf ->
                  TypeOf (ArgumentType (of_type_loc
                    (ext_type_of_type_loc_get_underlying_type type_loc)))
              | _ -> of_ext_type_kind cxtype
            end in
      make_paren (make_qual_type cxtype type_loc (Node.from_fun desc))

    and of_ext_type_kind cxtype =
      match ext_type_get_kind cxtype with
      | Paren -> ParenType (cxtype |> ext_get_inner_type |> of_cxtype)
      | Elaborated -> (* Here for Clang <3.9.0 *)
          let nested_name_specifier =
            ext_type_get_qualifier cxtype |>
            convert_nested_name_specifier in
          Elaborated {
            keyword = ext_elaborated_type_get_keyword cxtype;
            nested_name_specifier;
            named_type = ext_type_get_named_type cxtype |> of_cxtype;
          }
      | Attributed -> (* Here for Clang <8.0.0 *)
          Attributed {
            modified_type =
              ext_attributed_type_get_modified_type cxtype |> of_cxtype;
            attribute = attribute_of_cxtype cxtype;
          }
      | TemplateTypeParm ->
          TemplateTypeParm
            (cxtype |> ext_type_get_unqualified_type |>
              get_type_spelling)
      | SubstTemplateTypeParm ->
          SubstTemplateTypeParm
            (cxtype |> ext_type_get_unqualified_type |>
              get_type_spelling)
      | TemplateSpecialization ->
          let name =
            cxtype |>
            ext_template_specialization_type_get_template_name |>
            make_template_name in
          let args =
            List.init
              (ext_template_specialization_type_get_num_args cxtype)
            @@ fun i ->
              ext_template_specialization_type_get_argument cxtype i |>
              make_template_argument in
          TemplateSpecialization { name; args }
      | Builtin -> BuiltinType (get_type_kind cxtype)
      | Auto -> Auto
      | PackExpansion ->
          let pattern =
            ext_pack_expansion_get_pattern cxtype |> of_cxtype in
          PackExpansion pattern
      | Decltype ->
          let sub =
            ext_decltype_type_get_underlying_expr cxtype |>
            expr_of_cxcursor in
          Decltype sub
      | InjectedClassName ->
          let sub =
      ext_injected_class_name_type_get_injected_specialization_type
              cxtype |>
            of_cxtype in
          InjectedClassName sub
      | Using
          [@if [%meta Metapp.Exp.of_bool
            (Clangml_config.version.major >= 14)]] ->
          let sub = of_cxtype (ext_type_desugar cxtype) in
          if options.ignore_using_types then
            Node.force sub.desc
          else
            Using sub
      | Atomic ->
          Atomic (of_cxtype (ext_atomic_type_get_value_type cxtype))
      | TypeOfExpr ->
          TypeOf (ArgumentExpr (expr_of_cxcursor
            (ext_type_of_expr_type_get_underlying_expr cxtype)))
      | TypeOf ->
          TypeOf (ArgumentType (of_cxtype
            (ext_type_of_type_get_underlying_type cxtype)))
      | kind -> UnexposedType kind

    and of_cxtype cxtype =
      let desc () =
        match get_type_kind cxtype with
        | Invalid -> InvalidType
        | ConstantArray ->
            let element = cxtype |> get_array_element_type |> of_cxtype in
            let size = cxtype |> get_array_size in
            constant_array element size
        | Vector ->
            let element = cxtype |> get_element_type |> of_cxtype in
            let size = cxtype |> get_num_elements in
            Vector { element; size }
        | IncompleteArray ->
            let element = cxtype |> get_array_element_type |> of_cxtype in
            IncompleteArray element
        | VariableArray ->
            let element = cxtype |> get_array_element_type |> of_cxtype in
            let size =
              cxtype |> ext_variable_array_type_get_size_expr |>
              expr_of_cxcursor in
            VariableArray { element; size }
        | Pointer ->
            let pointee = cxtype |> get_pointee_type |> of_cxtype in
            Pointer pointee
        | LValueReference ->
            let pointee = cxtype |> get_pointee_type |> of_cxtype in
            LValueReference pointee
        | RValueReference ->
            let pointee = cxtype |> get_pointee_type |> of_cxtype in
            RValueReference pointee
        | Enum ->
            Enum (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | Record ->
            Record (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | Typedef ->
            Typedef (cxtype |> get_type_declaration |> ident_ref_of_cxcursor)
        | FunctionProto
        | FunctionNoProto ->
            let function_type =
              cxtype |> function_type_of_cxtype (parameters_of_cxtype cxtype) in
            FunctionType function_type
        | Complex ->
            let element_type = cxtype |> get_element_type |> of_cxtype in
            Complex element_type
        | MemberPointer ->
            let pointee = cxtype |> get_pointee_type |> of_cxtype in
            let class_ = cxtype |> type_get_class_type |> of_cxtype in
            MemberPointer { pointee; class_ }
        | _ ->
            of_ext_type_kind cxtype in
      if options.ignore_paren_in_types &&
        ext_type_get_kind cxtype = Paren then
        let inner = cxtype |> ext_get_inner_type |> of_cxtype in
        { inner with cxtype }
      else
        { cxtype; type_loc = None; desc = Node.from_fun desc;
          const = is_const_qualified_type cxtype;
          volatile = is_volatile_qualified_type cxtype;
          restrict = is_restrict_qualified_type cxtype; }

    and decl_of_cxcursor cursor =
      node ~cursor
        (Node.from_fun (fun () -> decl_desc_of_cxcursor cursor))

    and decl_desc_of_cxcursor cursor =
      try
        match get_cursor_kind cursor with
        | FunctionDecl ->
            Function (function_decl_of_cxcursor cursor)
        | FunctionTemplate ->
            make_template cursor begin
              decl_desc_of_cxcursor
                (ext_template_decl_get_templated_decl cursor)
            end
        | CXXMethod
        | ConversionFunction -> cxxmethod_decl_of_cxcursor cursor
        | VarDecl -> Var (var_decl_desc_of_cxcursor cursor)
        | StructDecl ->
            record_decl_of_cxcursor (Struct : clang_ext_elaboratedtypekeyword)
              cursor
        | UnionDecl ->
            record_decl_of_cxcursor (Union : clang_ext_elaboratedtypekeyword)
              cursor
        | ClassDecl ->
            record_decl_of_cxcursor (Class : clang_ext_elaboratedtypekeyword)
              cursor
        | ClassTemplate ->
            let cursor' = ext_template_decl_get_templated_decl cursor in
            let keyword =
              cursor' |>
              ext_tag_decl_get_tag_kind in
            make_template cursor
              (record_decl_of_cxcursor keyword cursor')
        | ClassTemplatePartialSpecialization ->
            let keyword = ext_tag_decl_get_tag_kind cursor in
            let decl () = record_decl_of_cxcursor keyword cursor in
            let result =
            TemplatePartialSpecialization
              { parameters = extract_template_parameters cursor;
                arguments = extract_template_arguments cursor;
                decl = node ~cursor (Node.from_fun decl) } in
            result
        | EnumDecl -> enum_decl_of_cxcursor cursor
        | TypedefDecl ->
            let name = get_cursor_spelling cursor in
            let underlying_type = cursor |>
              get_typedef_decl_underlying_type |> of_cxtype in
            TypedefDecl { name; underlying_type }
        | FieldDecl ->
            let name = get_cursor_spelling cursor in
            let qual_type =
              ext_declarator_decl_get_type_loc cursor |> of_type_loc in
            let bitwidth =
              if cursor_is_bit_field cursor then
                match last_child cursor with
                | Some bitwidth -> Some (expr_of_cxcursor bitwidth)
                | None -> raise Invalid_structure
              else
                None in
            let init =
              ext_field_decl_get_in_class_initializer cursor |>
              option_cursor_map expr_of_cxcursor in
            let attributes = attributes_of_decl cursor in
            Field { name; qual_type; bitwidth; init; attributes }
        | CXXAccessSpecifier ->
            AccessSpecifier (cursor |> get_cxxaccess_specifier)
        | UsingDirective ->
            let nested_name_specifier =
              cursor |> ext_decl_get_nested_name_specifier_loc |>
              convert_nested_name_specifier_loc in
            let namespace =
              ext_using_directive_decl_get_nominated_namespace cursor |>
              decl_of_cxcursor in
            UsingDirective { nested_name_specifier; namespace }
        | UsingDeclaration ->
            UsingDeclaration (ident_ref_of_cxcursor cursor)
        | Constructor ->
            let initializer_list =
              cursor |> list_of_cxxconstructor_initializers_map (fun init :
                   constructor_initializer ->
                let kind : constructor_initializer_kind =
                  if ext_cxxctor_initializer_is_base_initializer init then
                    Base {
                      qual_type = of_type_loc
                        (ext_cxxctor_initializer_get_type_source_info init);
                      pack_expansion =
                        ext_cxxctor_initializer_is_pack_expansion init;
                    }
                  else if
                    ext_cxxctor_initializer_is_delegating_initializer init then
                    Delegating (of_type_loc
                      (ext_cxxctor_initializer_get_type_source_info init))
                  else
                    let cursor = ext_cxxctor_initializer_get_member init in
                    Member {
                      indirect =
                        ext_cxxctor_initializer_is_indirect_member_initializer
                          init;
                      field =
                        node ~cursor
                          (Node.from_fun (fun () -> get_cursor_spelling cursor))
                    } in
                { kind;
                  init = expr_of_cxcursor
                    (ext_cxxctor_initializer_get_init init) }) in
            Constructor {
              class_name = get_cursor_spelling cursor;
              parameters = parameters_of_function_decl cursor;
              initializer_list;
              body = function_body_of_cxcursor cursor;
              defaulted = ext_cxxmethod_is_defaulted cursor;
              deleted = ext_function_decl_is_deleted cursor;
              implicit = ext_decl_is_implicit cursor;
              explicit = ext_cxxconstructor_is_explicit cursor;
              constexpr = ext_function_decl_is_constexpr cursor;
            }
        | Destructor ->
            let destructor_name = get_cursor_spelling cursor in
            Destructor {
              class_name = String.sub destructor_name 1
                (String.length destructor_name - 1);
              body = function_body_of_cxcursor cursor;
              defaulted = ext_cxxmethod_is_defaulted cursor;
              deleted = ext_function_decl_is_deleted cursor;
              exception_spec = extract_exception_spec (get_cursor_type cursor);
          }
        | TemplateTemplateParameter ->
            TemplateTemplateParameter (get_cursor_spelling cursor)
        | NamespaceAlias ->
            let alias = ident_ref_of_cxcursor cursor in
            let original =
              ident_ref_of_cxcursor (get_cursor_definition cursor) in
            NamespaceAlias { alias; original }
        | TypeAliasDecl ->
            let ident_ref = ident_ref_of_cxcursor cursor in
            let qual_type =
              get_typedef_decl_underlying_type cursor |> of_cxtype in
            TypeAlias { ident_ref; qual_type }
        | kind ->
            match ext_decl_get_kind cursor with
            | Empty -> EmptyDecl
            | LinkageSpec ->
                let language =
                  language_of_ids
                    (ext_linkage_spec_decl_get_language_ids cursor) in
                let decls =
                  list_of_children_map decl_of_cxcursor cursor in
                LinkageSpec { language; decls }
            | Friend -> (* No FriendDecl : cxcursortype in Clang <4.0.0 *)
                let friend_type = ext_friend_decl_get_friend_type cursor in
                if get_type_kind friend_type = Invalid then
                  let decl = ext_friend_decl_get_friend_decl cursor in
                  Friend (FriendDecl (decl_of_cxcursor decl))
                else
                  Friend (FriendType (of_cxtype friend_type))
            | Namespace ->
                let name = get_cursor_spelling cursor in
                let declarations =
                  list_of_children_map decl_of_cxcursor cursor in
                let inline = ext_namespace_decl_is_inline cursor in
                Namespace { name; declarations; inline }
            | StaticAssert ->
                (* No StaticAssert : cxcursortype in Clang <6.0.1 *)
                let constexpr, message =
                  match list_of_children cursor with
                  | [constexpr; message] ->
                      constexpr |> expr_of_cxcursor,
                      Some (message |> expr_of_cxcursor)
                  | [constexpr] ->
                      constexpr |> expr_of_cxcursor, None
                  | _ -> raise Invalid_structure in
                StaticAssert { constexpr; message }
            | VarTemplate ->
                make_template cursor begin
                  Var (var_decl_desc_of_cxcursor
                    (cursor |> ext_template_decl_get_templated_decl))
                end
            | TypeAliasTemplate ->
                (* No TypeAliasTemplateDecl : cxcursortype in Clang <3.8.0 *)
                make_template cursor begin
                  let ident_ref = ident_ref_of_cxcursor cursor in
                  let qual_type =
                    cursor |> ext_template_decl_get_templated_decl |>
                    get_typedef_decl_underlying_type |> of_cxtype in
                  TypeAlias { ident_ref; qual_type }
                end
            | IndirectField ->
                IndirectField (
                  (list_of_indirect_field_decl_chain_map decl_of_cxcursor
                     cursor))
            | Decomposition
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 4)]] ->
                let init =
                  match list_of_children cursor with
                  | [sub] -> Some (sub |> expr_of_cxcursor)
                  | [] -> None
                  | _ -> raise Invalid_structure in
                Decomposition {
                  bindings = List.init
                    (ext_decomposition_decl_get_bindings_count cursor)
                    begin fun i ->
                      ext_decomposition_decl_get_bindings cursor i |>
                      declaration_name_of_cxcursor
                    end;
                  init;
                }
            | Concept
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 9)]] ->
                let parameters = extract_template_parameters cursor in
                let name = declaration_name_of_cxcursor cursor in
                let constraint_expr =
                  cursor |> ext_concept_decl_get_constraint_expr |>
                  expr_of_cxcursor in
                Concept { parameters; name; constraint_expr }
            | Export
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 4)]] ->
                Export (list_of_decl_context_map decl_of_cxcursor cursor)
            | ext_kind -> UnknownDecl (kind, ext_kind)
      with Invalid_structure ->
        UnknownDecl (get_cursor_kind cursor, ext_decl_get_kind cursor)

    and function_body_of_cxcursor cursor : stmt option =
      if ext_function_decl_does_this_declaration_have_abody cursor then
        let cursor = ext_function_decl_get_body cursor in
        match get_cursor_kind cursor with
        | CompoundStmt
        | CXXTryStmt ->
            Some (stmt_of_cxcursor cursor)
        | _ -> None
      else
        None

    and parameters_of_function_decl cursor =
      { non_variadic =
      List.init (ext_function_decl_get_num_params cursor) (fun i ->
        parameter_of_cxcursor (ext_function_decl_get_param_decl cursor i));
      variadic = is_function_type_variadic (get_cursor_type cursor) }

    and parameters_of_function_decl_or_proto cursor =
      if cursor |> get_cursor_type |> get_type_kind = FunctionProto then
        Some (parameters_of_function_decl cursor)
      else
        None

    and parameter_of_cxcursor cursor =
      let desc () =
        (*
        let _namespaces, others =  |>
          extract begin fun c : string option ->
            match get_cursor_kind c with
            | NamespaceRef -> Some (get_cursor_spelling c)
            | _ -> None
          end in
        *)
        let type_loc = cursor |> ext_declarator_decl_get_type_loc in
        let qual_type =
          if type_loc |> ext_type_loc_get_class = InvalidTypeLoc then
            cursor |> get_cursor_type |> of_cxtype
          else
            type_loc|> of_type_loc in
        { name = cursor |> get_cursor_spelling;
          qual_type;
          default =
            if ext_var_decl_has_init cursor then
              let default = Option.get (last_child cursor) in
              Some (default |> expr_of_cxcursor)
            else
              None } in
      node ~cursor (Node.from_fun desc)

    and function_type_of_decl cursor =
      let parameters = parameters_of_function_decl_or_proto cursor in
      let type_loc = ext_declarator_decl_get_type_loc cursor in
      if ext_type_loc_get_class type_loc = InvalidTypeLoc then
        function_type_of_cxtype parameters (get_cursor_type cursor)
      else
        function_type_of_type_loc parameters type_loc

    and function_decl_of_cxcursor cursor =
      let cursor =
        match get_cursor_kind cursor with
        | FunctionTemplate ->
            ext_template_decl_get_templated_decl cursor
        | _ ->
            cursor in
      (* Hack for Clang 3.4 and 3.5! See current_decl declaration. *)
      current_decl := cursor;
      let nested_name_specifier =
        cursor |> ext_decl_get_nested_name_specifier_loc |>
        convert_nested_name_specifier_loc in
      let name = declaration_name_of_cxcursor cursor in
      let body = function_body_of_cxcursor cursor in
      let function_type = function_type_of_decl cursor in
      {
        linkage = get_cursor_linkage cursor;
        function_type;
        nested_name_specifier; name; body;
        deleted = ext_function_decl_is_deleted cursor;
        constexpr = ext_function_decl_is_constexpr cursor;
        attributes = attributes_of_decl cursor;
        inline_specified = ext_function_decl_is_inline_specified cursor;
        inlined = ext_function_decl_is_inlined cursor;
        has_written_prototype = ext_function_decl_has_written_prototype cursor;
      }

    and attributes_of_decl cursor =
      if ext_decl_has_attrs cursor then
        List.init (ext_decl_get_attr_count cursor)
          (fun i -> attribute_of_cxcursor (ext_decl_get_attr cursor i))
      else
        []

    and cxxmethod_decl_of_cxcursor cursor =
      let type_ref =
        ext_cxxmethod_decl_get_parent cursor |>
        get_cursor_type |> of_cxtype in
      let function_decl = function_decl_of_cxcursor cursor in
      let num_templates =
        ext_function_decl_get_num_template_parameter_lists cursor in
      let templates =
        List.init num_templates (fun index ->
          extract_template_parameter_list
            (ext_function_decl_get_template_parameter_list cursor index)) in
      let add_template (decl : decl_desc) parameters : decl_desc =
        TemplateDecl { parameters; decl = node ~cursor (Node.from_val decl) } in
      List.fold_left add_template (CXXMethod {
        type_ref; function_decl;
        defaulted = ext_cxxmethod_is_defaulted cursor;
        static = cxxmethod_is_static cursor;
        binding =
          if cxxmethod_is_pure_virtual cursor then
            PureVirtual
          else if cxxmethod_is_virtual cursor then
            Virtual
          else
            NonVirtual;
        const = ext_cxxmethod_is_const cursor;
        implicit = ext_decl_is_implicit cursor;
      }) templates

    and parameter_of_cxtype cxtype =
      let qual_type = of_cxtype cxtype in
      let desc () = { name = ""; qual_type; default = None } in
      node ~qual_type (Node.from_fun desc)

    and parameters_of_cxtype cxtype =
      if cxtype |> get_type_kind = FunctionProto then
        let non_variadic =
          List.init (get_num_arg_types cxtype) @@ fun i ->
            parameter_of_cxtype (get_arg_type cxtype i) in
        let variadic = is_function_type_variadic cxtype in
        Some { non_variadic; variadic }
      else
        None

    and parameters_of_type_loc type_loc =
      let cxtype = ext_type_loc_get_type type_loc in
      if cxtype |> get_type_kind = FunctionProto then
        let non_variadic =
          List.init (get_num_arg_types cxtype) @@ fun i ->
            let cursor = ext_function_type_loc_get_param type_loc i in
            if get_cursor_kind cursor = InvalidCode then
              parameter_of_cxtype (get_arg_type cxtype i)
            else
              parameter_of_cxcursor cursor in
        let variadic = is_function_type_variadic cxtype in
        Some { non_variadic; variadic }
      else
        None

    and function_type_of_cxtype parameters cxtype =
      let result = cxtype |> get_result_type |> of_cxtype in
      function_type_of_cxtype_result parameters cxtype result

    and function_type_of_cxtype_result parameters cxtype result =
      let calling_conv = cxtype |> get_function_type_calling_conv in
      let exception_spec : exception_spec option =
        extract_exception_spec cxtype in
      let ref_qualifier = cxtype |> type_get_cxxref_qualifier in
      { calling_conv; result; parameters; exception_spec; ref_qualifier }

    and function_type_of_type_loc parameters type_loc =
      let cxtype = ext_type_loc_get_type type_loc in
      let result =
        type_loc |> ext_function_type_loc_get_return_loc |> of_type_loc in
      function_type_of_cxtype_result parameters cxtype result

    and extract_exception_spec cxtype =
      match ext_function_proto_type_get_exception_spec_type cxtype with
      | NoExceptionSpecification -> None
      | DynamicNone -> Some (Throw [])
      | Dynamic ->
          let throws =
            List.init (ext_function_proto_type_get_num_exceptions cxtype)
              begin fun index ->
                ext_function_proto_type_get_exception_type cxtype index |>
                of_cxtype
              end in
          Some (Throw throws)
      | BasicNoexcept -> Some (Noexcept { expr = None; evaluated = None })
      | DependentNoexcept ->
          let expr =
            ext_function_proto_type_get_noexcept_expr cxtype |>
            expr_of_cxcursor in
          Some (Noexcept { expr = Some expr; evaluated = None })
      | NoexceptFalse ->
          let expr = ext_function_proto_type_get_noexcept_expr cxtype |>
            expr_of_cxcursor in
          Some (Noexcept { expr = Some expr; evaluated = Some false })
      | NoexceptTrue ->
          let expr = ext_function_proto_type_get_noexcept_expr cxtype |>
            expr_of_cxcursor in
          Some (Noexcept { expr = Some expr; evaluated = Some true })
      | other -> Some (Other other)

    and var_decl_of_cxcursor cursor =
      node ~cursor (Node.from_fun (fun () -> var_decl_desc_of_cxcursor cursor))

    and var_decl_desc_of_cxcursor cursor =
      let linkage = cursor |> get_cursor_linkage in
      let var_name = get_cursor_spelling cursor in
      let var_type = of_type_loc (ext_declarator_decl_get_type_loc cursor) in
      let var_init : 'a option =
        if ext_var_decl_has_init cursor then
          begin
            let init_value = Option.get (last_child cursor) in
            option_call_expr_of_cxcursor init_value
          end
        else
          None in
      { linkage; var_name; var_type; var_init;
        constexpr = ext_var_decl_is_constexpr cursor;
        attributes = attributes_of_decl cursor; }

    and enum_decl_of_cxcursor cursor =
      let name = get_cursor_spelling cursor in
      let constants =
        cursor |> list_of_children_filter_map (fun cursor ->
          match get_cursor_kind cursor with
          | EnumConstantDecl -> Some (enum_constant_of_cxcursor cursor)
          | _ -> None) in
      let complete_definition = ext_tag_decl_is_complete_definition cursor in
      let attributes = attributes_of_decl cursor in
      EnumDecl { name; constants; complete_definition; attributes }

    and enum_constant_of_cxcursor cursor =
      let desc () =
        let constant_name = get_cursor_spelling cursor in
        let constant_init =
          match last_child cursor with
          | Some init -> Some (expr_of_cxcursor init)
          | None -> None in
        { constant_name; constant_init } in
      node ~cursor (Node.from_fun desc)

    and base_specifier_of_cxcursor cursor =
      { qual_type = of_type_loc (ext_cursor_get_type_loc cursor);
        virtual_base = is_virtual_base cursor;
        access_specifier = get_cxxaccess_specifier cursor;
      }

    and attribute_of_cxcursor (cursor : cxcursor) : attribute =
      let desc () =
        Attributes.convert cursor expr_of_cxcursor decl_of_cxcursor of_type_loc
          convert_declaration_name Fun.id in
      node ~cursor (Node.from_fun desc)

    and record_decl_of_cxcursor (keyword : clang_ext_elaboratedtypekeyword)
        cursor =
      let attributes =
        list_of_iter_map attribute_of_cxcursor
          (fun f -> iter_decl_attributes f cursor) in
      let name = get_cursor_spelling cursor in
      let nested_name_specifier =
        cursor |> ext_decl_get_nested_name_specifier_loc |>
        convert_nested_name_specifier_loc in
      let final =
        attributes |> List.exists (fun (attr : attribute) ->
          Node.force attr.desc = (Other Final : attribute_desc)) in
      let bases =
        list_of_iter_map base_specifier_of_cxcursor
          (fun f -> iter_cxxrecorddecl_bases f cursor) in
      let fields =
        list_of_iter_filter_map (fun cursor ->
            if ext_decl_is_implicit cursor &&
               match ext_decl_get_kind cursor with
               | CXXConstructor
               | CXXDestructor -> options.ignore_implicit_constructors
               | Field when get_cursor_spelling cursor = "" ->
                   options.ignore_anonymous_fields
               | IndirectField -> options.ignore_indirect_fields
               | CXXRecord
                    when ext_record_decl_is_injected_class_name cursor ->
                   options.ignore_injected_class_names
               | CXXMethod -> options.ignore_implicit_methods
               | _ -> false then
              None
            else
              Some (decl_of_cxcursor cursor))
          (fun f -> iter_decl_context f cursor) in
      let complete_definition = ext_tag_decl_is_complete_definition cursor in
      let is_injected_class_name =
        ext_record_decl_is_injected_class_name cursor in
      RecordDecl {
        keyword; attributes; nested_name_specifier; name; bases; fields; final;
        complete_definition; is_injected_class_name; }

    and stmt_of_cxcursor cursor =
      let desc () =
        try
          match get_cursor_kind cursor with
          | NullStmt ->
              Null
          | CompoundStmt ->
              let items = list_of_children_map stmt_of_cxcursor cursor in
              Compound items
          | ForStmt ->
              let children_set = ext_for_stmt_get_children_set cursor in
              let queue = Queue.create () in
              cursor |> iter_children (fun cur -> Queue.add cur queue);
              let init =
                if children_set land 1 <> 0 then
                  Some (stmt_of_cxcursor (Queue.pop queue))
                else
                  None in
              let condition_variable =
                if children_set land 2 <> 0 then
                  Some (var_decl_of_cxcursor (Queue.pop queue))
                else
                  None in
              let cond =
                if children_set land 4 <> 0 then
                  Some (expr_of_cxcursor (Queue.pop queue))
                else
                  None in
              let inc =
                if children_set land 8 <> 0 then
                  Some (stmt_of_cxcursor (Queue.pop queue))
                else
                  None in
              let body = stmt_of_cxcursor (Queue.pop queue) in
              assert (Queue.is_empty queue);
              For { init; condition_variable; cond; inc; body }
          | IfStmt ->
              let init =
                ext_if_stmt_get_init cursor |>
                option_cursor_map stmt_of_cxcursor in
              let condition_variable =
                ext_if_stmt_get_condition_variable cursor |>
                option_cursor_map var_decl_of_cxcursor in
              let cond =
                ext_if_stmt_get_cond cursor |>
                expr_of_cxcursor in
              let then_branch =
                ext_if_stmt_get_then cursor |>
                stmt_of_cxcursor in
              let else_branch =
                ext_if_stmt_get_else cursor |>
                option_cursor_map stmt_of_cxcursor in
              If { init; condition_variable; cond; then_branch; else_branch }
          | SwitchStmt ->
              let children_set = ext_switch_stmt_get_children_set cursor in
              let queue = Queue.create () in
              cursor |> iter_children (fun cur -> Queue.add cur queue);
              let init =
                if children_set land 1 <> 0 then
                  Some (ext_switch_stmt_get_init cursor |> stmt_of_cxcursor)
                else
                  None in
              let condition_variable =
                if children_set land 2 <> 0 then
                  Some (var_decl_of_cxcursor (Queue.pop queue))
                else
                  None in
              let cond = expr_of_cxcursor (Queue.pop queue) in
              let body = stmt_of_cxcursor (Queue.pop queue) in
              assert (Queue.is_empty queue);
              Switch { init; condition_variable; cond; body }
          | CaseStmt ->
              let lhs, rhs, body =
                match list_of_children cursor with
                | [lhs; rhs; body] ->
                    lhs, Some (expr_of_cxcursor rhs), body
                | [lhs; body] ->
                    lhs, None, body
                | _ ->
                    raise Invalid_structure in
              let lhs = expr_of_cxcursor lhs in
              let body = stmt_of_cxcursor body in
              Case { lhs; rhs; body }
          | DefaultStmt ->
              let body =
                match list_of_children cursor with
                | [body] -> stmt_of_cxcursor body
                | _ ->
                    raise Invalid_structure in
              Default body
          | WhileStmt ->
              let children_set = ext_while_stmt_get_children_set cursor in
              let queue = Queue.create () in
              cursor |> iter_children (fun cur -> Queue.add cur queue);
              let condition_variable =
                if children_set land 1 <> 0 then
                  Some (var_decl_of_cxcursor (Queue.pop queue))
                else
                  None in
              let cond = expr_of_cxcursor (Queue.pop queue) in
              let body = stmt_of_cxcursor (Queue.pop queue) in
              assert (Queue.is_empty queue);
              While { condition_variable; cond; body }
          | DoStmt ->
              let body, cond =
                match list_of_children cursor with
                | [body; cond] -> stmt_of_cxcursor body, expr_of_cxcursor cond
                | _ -> raise Invalid_structure in
              Do { body; cond }
          | LabelStmt ->
              let label = cursor |> get_cursor_spelling in
              let body =
                match list_of_children cursor with
                | [body] -> stmt_of_cxcursor body
                | _ -> raise Invalid_structure in
              Label { label; body }
          | GotoStmt ->
              let label =
                match list_of_children cursor with
                | [label] -> label |> get_cursor_spelling
                | _ -> raise Invalid_structure in
              Goto label
          | IndirectGotoStmt ->
              let target =
                match list_of_children cursor with
                | [target] -> expr_of_cxcursor target
                | _ -> raise Invalid_structure in
              IndirectGoto target
          | ContinueStmt ->
              Continue
          | BreakStmt ->
              Break
          | DeclStmt ->
              let decl = list_of_children_map decl_of_cxcursor cursor in
              Decl decl
          | ReturnStmt ->
              let value =
                match list_of_children cursor with
                | [value] -> Some (expr_of_cxcursor value)
                | [] -> None
                | _ -> raise Invalid_structure in
              Return value
          | GCCAsmStmt ->
              Asm (asm_of_cxcursor GCC cursor)
          | MSAsmStmt ->
              Asm (asm_of_cxcursor MS cursor)
          | CXXForRangeStmt ->
              ForRange {
                var =
                  ext_cxxfor_range_stmt_get_loop_variable cursor |>
                  var_decl_of_cxcursor;
                range =
                  ext_cxxfor_range_stmt_get_range_init cursor |>
                  expr_of_cxcursor;
                body =
                  ext_cxxfor_range_stmt_get_body cursor |>
                  stmt_of_cxcursor;
              }
          | CXXTryStmt ->
              let try_block, handlers =
                match list_of_children cursor with
                | try_block :: handlers ->
                    try_block |> stmt_of_cxcursor,
                    handlers |> List.map catch_of_cxcursor
                | _ -> raise Invalid_structure in
              Try { try_block; handlers }
          | UnexposedStmt ->
              begin
                match ext_stmt_get_kind cursor with
                | AttributedStmt ->
                    let attributes =
                      list_of_iter (ext_attributed_stmt_get_attrs cursor) |>
                      List.map attribute_of_cxcursor in
                    AttributedStmt {
                      attributes;
                      sub_stmts =
                        list_of_children_map stmt_of_cxcursor cursor;
                    }
                | _ -> raise Invalid_structure
              end
          | _ ->
              let decl_desc = decl_desc_of_cxcursor cursor in
              match decl_desc with
              | UnknownDecl _ ->
                  Expr (expr_of_cxcursor cursor)
              | _ ->
                  Decl [node ~cursor (Node.from_val decl_desc)]
        with Invalid_structure ->
          UnknownStmt (get_cursor_kind cursor, ext_stmt_get_kind cursor) in
      node ~cursor (Node.from_fun desc)

    and catch_of_cxcursor cursor : catch =
      match list_of_children cursor with
      | [block] ->
          { parameter = None;
            block = block |> stmt_of_cxcursor;
          }
      | [var; block] ->
          { parameter =
              Some (get_cursor_spelling var, get_cursor_type var |> of_cxtype);
            block = block |> stmt_of_cxcursor;
          }
      | _ -> raise Invalid_structure

    and asm_of_cxcursor asm_compiler_extension cursor =
      let asm_outputs =
        List.init (ext_asm_stmt_get_num_outputs cursor) (fun i -> {
          asm_constraint = ext_asm_stmt_get_output_constraint cursor i;
          asm_expr = ext_asm_stmt_get_output_expr cursor i |> expr_of_cxcursor;
        }) in
      let asm_inputs =
        List.init (ext_asm_stmt_get_num_inputs cursor) (fun i -> {
          asm_constraint = ext_asm_stmt_get_input_constraint cursor i;
          asm_expr = ext_asm_stmt_get_input_expr cursor i |> expr_of_cxcursor;
        }) in {
      asm_compiler_extension; asm_inputs; asm_outputs;
      asm_string = ext_asm_stmt_get_asm_string cursor;
    }

    and expr_of_cxcursor cursor =
      let desc () =
        match expr_desc_of_cxcursor cursor with
        | Paren subexpr when options.ignore_paren ->
            Node.force subexpr.desc
        | Cast { kind = Implicit; operand; _ }
          when options.ignore_implicit_cast ->
            Node.force operand.desc
        | desc -> desc in
      node ~cursor (Node.from_fun desc)

    and expr_desc_of_cxcursor cursor =
      let kind = get_cursor_kind cursor in
      try
        match kind with
        | IntegerLiteral ->
            let i = ext_integer_literal_get_value cursor in
            let literal =
              make_integer_literal i (get_type_kind (get_cursor_type cursor)) in
            IntegerLiteral literal
        | FloatingLiteral ->
            let f = ext_floating_literal_get_value cursor in
            let literal =
              match
                if options.convert_floating_literals then
                  float_of_cxfloat_opt f
                else
                  None
              with
              | None -> CXFloat f
              | Some f -> Float f in
            FloatingLiteral literal
        | StringLiteral ->
            StringLiteral {
              bytes = ext_string_literal_get_bytes cursor;
              byte_width = ext_string_literal_get_char_byte_width cursor;
              string_kind = ext_string_literal_get_kind cursor;
            }
        | CharacterLiteral ->
            let kind = ext_character_literal_get_character_kind cursor in
            let value = ext_character_literal_get_value cursor in
            CharacterLiteral { kind; value }
        | ImaginaryLiteral ->
            let sub_expr =
              match list_of_children cursor with
              | [operand] -> expr_of_cxcursor operand
              | _ -> raise Invalid_structure in
            ImaginaryLiteral sub_expr
        | CXXBoolLiteralExpr ->
            BoolLiteral (ext_cxxbool_literal_expr_get_value cursor)
        | CXXNullPtrLiteralExpr ->
            NullPtrLiteral
        | UnaryOperator ->
            let operand =
              match list_of_children cursor with
              | [operand] -> expr_of_cxcursor operand
              | _ -> raise Invalid_structure in
            let kind = ext_unary_operator_get_opcode cursor in
            UnaryOperator { kind; operand }
        | BinaryOperator | CompoundAssignOperator ->
            let lhs, rhs =
              match list_of_children cursor with
              | [lhs; rhs] -> expr_of_cxcursor lhs, expr_of_cxcursor rhs
              | _ -> raise Invalid_structure in
            let kind = ext_binary_operator_get_opcode cursor in
            BinaryOperator { lhs; kind; rhs }
        | DeclRefExpr ->
            begin match ext_stmt_get_kind cursor with
            | SubstNonTypeTemplateParmExpr ->
                SubstNonTypeTemplateParm
                  (ext_subst_non_type_template_parm_expr_get_replacement cursor
                    |> expr_of_cxcursor)
            | _ ->
              DeclRef (ident_ref_of_cxcursor cursor)
            end
        | CallExpr ->
            begin
            let list_args cursor =
              cursor |> list_of_children_filter_map (fun cursor ->
                if is_not_ref cursor then
                  Some (expr_of_cxcursor cursor)
                else
                  None) in
            match ext_stmt_get_kind cursor with
            | CXXConstructExpr ->
                Construct {
                  qual_type = cursor |> get_cursor_type |> of_cxtype;
                  args = list_args cursor;
                }
            | CXXTemporaryObjectExpr ->
                TemporaryObject {
                  qual_type = cursor |> get_cursor_type |> of_cxtype;
                  args = list_args cursor;
                }
            | CXXUnresolvedConstructExpr ->
                UnresolvedConstruct {
                  qual_type = cursor |> get_cursor_type |> of_cxtype;
                  args = list_args cursor;
                }
            | _ ->
                let callee = ext_call_expr_get_callee cursor in
                if get_cursor_kind callee = InvalidCode then
                  raise Invalid_structure
                else
                  let callee = callee |> expr_of_cxcursor in
                  Call {
                    callee;
                    args = List.init (ext_call_expr_get_num_args cursor) begin
                      fun i ->
                        ext_call_expr_get_arg cursor i |> expr_of_cxcursor
                    end
                  }
            end
        | CStyleCastExpr ->
            cast_of_cxcursor CStyle cursor
        | MemberRefExpr ->
            let base =
              match
                list_of_children cursor |> filter_out_prefix_from_list begin
                  fun cursor ->
                    match get_cursor_kind cursor with
                    | TypeRef | OverloadedDeclRef -> true
                    | _ -> false
                end
              with
              | lhs :: _ -> Some (lhs |> expr_of_cxcursor)
              | [] -> None in
            let field = field_of_cxcursor cursor in
            let arrow = ext_member_ref_expr_is_arrow cursor in
            Member { base; arrow; field }
        | ArraySubscriptExpr ->
            let base, index =
              match list_of_children cursor with
              | [base; index] -> expr_of_cxcursor base, expr_of_cxcursor index
              | _ -> raise Invalid_structure in
            ArraySubscript { base; index }
        | ConditionalOperator ->
            let cond, then_branch, else_branch =
              match list_of_children cursor |> List.map expr_of_cxcursor with
              | [cond; then_branch; else_branch] ->
                  cond, Some then_branch, else_branch
              | _ -> raise Invalid_structure in
            ConditionalOperator { cond; then_branch; else_branch }
        | ParenExpr ->
            let subexpr =
              match list_of_children cursor with
              | [subexpr] -> expr_of_cxcursor subexpr
              | _ -> raise Invalid_structure in
            Paren subexpr
        | AddrLabelExpr ->
            let label =
              match list_of_children cursor with
              | [label] -> get_cursor_spelling label
              | _ -> raise Invalid_structure in
            AddrLabel label
        | InitListExpr ->
            let cursor = Init_list.get_form options.init_list_form cursor in
            let inits =
              List.init (ext_init_list_expr_get_num_inits cursor)
                (fun i -> ext_init_list_expr_get_init cursor i) in
            InitList (inits |> List.map expr_of_cxcursor)
        | CompoundLiteralExpr ->
            let qual_type = cursor |> get_cursor_type |> of_cxtype in
            let init =
              match list_of_children cursor |> filter_out_prefix_from_list begin
                  fun cursor ->
                    match get_cursor_kind cursor with
                    | TypeRef -> true
                    | _ -> false
                end with
              | [init] -> init |> expr_of_cxcursor
              | _ -> raise Invalid_structure in
            CompoundLiteral { qual_type; init }
        | UnaryExpr ->
            begin
              match ext_stmt_get_kind cursor with
              | CXXNoexceptExpr ->
                  let sub =
                    match list_of_children cursor with
                    | [sub] -> sub |> expr_of_cxcursor
                    | _ -> raise Invalid_structure in
                  NoexceptExpr sub
              | _ ->
                  unary_expr_of_cxcursor cursor
            end
        | GenericSelectionExpr ->
            begin
              let controlling_expr, assocs =
                match list_of_children cursor with
                | [] -> raise Invalid_structure
                | controlling_expr :: assocs ->
                    controlling_expr |> expr_of_cxcursor,
                    assocs |> List.mapi @@ fun i sub_cursor ->
                      let ty =
                        ext_generic_selection_expr_get_assoc_type cursor i in
                      let ty : qual_type option =
                        if get_type_kind ty = Invalid then
                          None
                        else
                          Some (ty |> of_cxtype) in
                      (ty, sub_cursor |> expr_of_cxcursor) in
              GenericSelection { controlling_expr; assocs }
            end
        | LambdaExpr ->
            lambda_expr_of_cxcursor cursor
        | CXXThisExpr -> This
        | CXXNewExpr ->
            begin
              let placement_args =
                List.init (cursor |> ext_cxxnew_expr_get_num_placement_args)
                  begin fun i ->
                    ext_cxxnew_expr_get_placement_arg cursor i |>
                    expr_of_cxcursor
                  end in
              let qual_type =
                cursor |> ext_cxxnew_expr_get_allocated_type_loc |>
                of_type_loc in
              let array_size =
                cursor |> ext_cxxnew_expr_get_array_size |>
                option_cursor_map expr_of_cxcursor in
              let init =
                cursor |> ext_cxxnew_expr_get_initializer |>
                option_call_expr_of_cxcursor in
              New { placement_args; qual_type; array_size; init }
            end
        | CXXDeleteExpr ->
            let argument =
              match list_of_children cursor with
              | [operand] -> operand |> expr_of_cxcursor
              | _ -> raise Invalid_structure in
            Delete { argument;
              global_delete = ext_cxxdelete_expr_is_global_delete cursor;
              array_form = ext_cxxdelete_expr_is_array_form cursor; }
        | CXXTypeidExpr ->
            let argument =
              if ext_cxxtypeid_expr_is_type_operand cursor then
                ArgumentType (ext_cxxtypeid_expr_get_type_operand cursor |>
                  of_type_loc)
              else
                ArgumentExpr (ext_cxxtypeid_expr_get_expr_operand cursor |>
                  expr_of_cxcursor) in
            Typeid argument
        | PackExpansionExpr ->
            let sub =
              match list_of_children cursor with
              | [sub] -> expr_of_cxcursor sub
              | _ -> raise Invalid_structure in
            PackExpansionExpr sub
        | SizeOfPackExpr ->
            SizeOfPack (
              ext_size_of_pack_expr_get_pack cursor |> ident_ref_of_cxcursor)
        | CXXFunctionalCastExpr ->
            cast_of_cxcursor Functional cursor
        | CXXStaticCastExpr ->
            cast_of_cxcursor Static cursor
        | CXXDynamicCastExpr ->
            cast_of_cxcursor Dynamic cursor
        | CXXConstCastExpr ->
            cast_of_cxcursor Const cursor
        | CXXThrowExpr ->
            let sub =
              match list_of_children cursor with
              | [sub] -> Some (expr_of_cxcursor sub)
              | [] -> None
              | _ -> raise Invalid_structure in
            ThrowExpr sub
        | TemplateRef ->
            TemplateRef (ident_ref_of_cxcursor cursor)
        | OverloadedDeclRef ->
            OverloadedDeclRef (ident_ref_of_cxcursor cursor)
        | StmtExpr ->
            let sub =
              match list_of_children cursor with
              | [sub] -> sub
              | _ -> raise Invalid_structure in
            StmtExpr (stmt_of_cxcursor sub)
        | UnexposedExpr ->
            begin
              match ext_stmt_get_kind cursor with
              | ImplicitCastExpr ->
                  cast_of_cxcursor Implicit cursor
              | BinaryConditionalOperator ->
                  let cond, else_branch =
                    match
                      list_of_children_map expr_of_cxcursor cursor with
                    | [_; cond; _; else_branch] ->
                        cond, else_branch
                    | _ ->
                        raise Invalid_structure in
                  ConditionalOperator { cond; then_branch = None; else_branch }
              | UnaryExprOrTypeTraitExpr -> (* for Clang 3.8.1 *)
                  unary_expr_of_cxcursor cursor
              | PredefinedExpr ->
                  let kind = ext_predefined_expr_get_ident_kind cursor in
                  let function_name =
                    predefined_expr_get_function_name cursor !current_decl in
                  Predefined { kind; function_name }
              | ExprWithCleanups ->
                  let sub =
                    match list_of_children cursor with
                    | [sub] -> expr_of_cxcursor sub
                    | _ -> raise Invalid_structure in
                  if options.ignore_expr_with_cleanups then
                    Node.force sub.desc
                  else
                    ExprWithCleanups sub
              | MaterializeTemporaryExpr ->
                  let sub =
                    match list_of_children cursor with
                    | [sub] -> expr_of_cxcursor sub
                    | _ -> raise Invalid_structure in
                  if options.ignore_materialize_temporary_expr then
                    Node.force sub.desc
                  else
                    MaterializeTemporaryExpr sub
              | CXXBindTemporaryExpr ->
                  let sub =
                    match list_of_children cursor with
                    | [sub] -> expr_of_cxcursor sub
                    | _ -> raise Invalid_structure in
                  if options.ignore_bind_temporary_expr then
                    Node.force sub.desc
                  else
                    BindTemporaryExpr sub
              | CXXDefaultArgExpr ->
                  DefaultArg
              | CXXStdInitializerListExpr ->
                  StdInitializerList
                    (list_of_children_map expr_of_cxcursor cursor)
              | ImplicitValueInitExpr ->
                  ImplicitValueInit
                    (cursor |> get_cursor_type |> of_cxtype)
              | DesignatedInitExpr ->
                  let designators =
                    List.init (ext_designated_init_expr_size cursor) (fun i ->
                      match ext_designated_init_expr_get_kind cursor i with
                      | FieldDesignator ->
                          let field =
                            ext_designated_init_expr_get_field cursor i in
                          FieldDesignator (get_cursor_spelling field)
                      | ArrayDesignator ->
                          let index =
                            ext_designated_init_expr_get_array_index cursor i in
                          ArrayDesignator (expr_of_cxcursor index)
                      | ArrayRangeDesignator ->
                          let range_start =
                            ext_designated_init_expr_get_array_range_start
                              cursor i in
                          let range_end =
                            ext_designated_init_expr_get_array_range_end
                              cursor i in
                          ArrayRangeDesignator (
                            expr_of_cxcursor range_start,
                            expr_of_cxcursor range_end)) in
                  let init =
                    ext_designated_init_expr_get_init cursor |>
                    expr_of_cxcursor in
                  DesignatedInit { designators; init }
              | CXXFoldExpr
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version >=
                    { major = 3; minor = 6; subminor = 0 })]] ->
                  let lhs, rhs =
                    match list_of_children cursor with
                    | [lhs; rhs] ->
                        Some (expr_of_cxcursor lhs),
                        Some (expr_of_cxcursor rhs)
                    | [sub] ->
                        if ext_cxxfold_expr_is_right_fold cursor then
                          Some (expr_of_cxcursor sub), None
                        else
                          None, Some (expr_of_cxcursor sub)
                    | _ -> raise Invalid_structure in
                  let operator = ext_cxxfold_expr_get_operator cursor in
                  Fold { lhs; operator; rhs }
              | ArrayInitLoopExpr
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 4)]] ->
                  let common_expr, sub_expr =
                    match list_of_children cursor with
                    | [common_expr; sub_expr] ->
                        common_expr |> expr_of_cxcursor,
                        sub_expr |> expr_of_cxcursor
                      | _ -> raise Invalid_structure in
                  ArrayInitLoop { common_expr; sub_expr }
              | ArrayInitIndexExpr
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 4)]] ->
                  ArrayInitIndex
              | RequiresExpr
                [@if [%meta Metapp.Exp.of_bool
                  (Clangml_config.version.major >= 10)]] ->
    let extract_expr_requirement requirement =
      let return_type_type_constraint =
        ext_expr_requirement_return_type_get_type_constraint requirement |>
        option_cursor_map expr_of_cxcursor in
      { expr = ext_expr_requirement_get_expr requirement |> expr_of_cxcursor;
        return_type_type_constraint =
          return_type_type_constraint |> Option.map (fun type_constraint ->
            { type_constraint;
              parameters =
ext_expr_requirement_return_type_get_type_constraint_template_parameter_list
                requirement |> extract_template_parameter_list; })} in

    let extract_requirement requirement : requirement =
      match ext_requirement_get_kind requirement with
      | Type -> Type (ext_type_requirement_get_type requirement |> of_type_loc)
      | Simple -> Simple (extract_expr_requirement requirement)
      | Compound -> Compound (extract_expr_requirement requirement)
      | Nested ->
          let expr =
            ext_nested_requirement_get_constraint_expr requirement |>
            expr_of_cxcursor in
          Nested expr in

                  Requires {
                    local_parameters =
                      List.init
                        (ext_requires_expr_get_local_parameter_count cursor)
                        (fun i ->
                          ext_requires_expr_get_local_parameter cursor i |>
                          parameter_of_cxcursor);
                    requirements =
                      List.init
                        (ext_requires_expr_get_requirement_count cursor)
                        (fun i ->
                          ext_requires_expr_get_requirement cursor i |>
                          extract_requirement);
                  }
              | ParenListExpr ->
                  let exprs =
                    List.map expr_of_cxcursor (list_of_children cursor) in
                  ParenList exprs
              | AtomicExpr ->
                  let op = ext_atomic_expr_get_op cursor in
                  let args =
                    List.map expr_of_cxcursor (list_of_children cursor) in
                  Atomic { op; args }
              | kind -> UnexposedExpr kind
            end
        | _ ->
            UnknownExpr (kind, ext_stmt_get_kind cursor)
      with Invalid_structure ->
        UnknownExpr (kind, ext_stmt_get_kind cursor)

    and field_of_cxcursor cursor =
      match ext_stmt_get_kind cursor with
      | CXXPseudoDestructorExpr ->
          PseudoDestructor {
            nested_name_specifier =
              ext_decl_get_nested_name_specifier_loc cursor |>
              convert_nested_name_specifier_loc;
            qual_type =
              cursor |>
              ext_cxxpseudo_destructor_expr_get_destroyed_type_loc |>
              of_type_loc }
      | CXXDependentScopeMemberExpr ->
          DependentScopeMember {
            ident_ref = ident_ref_of_cxcursor cursor;
            template_arguments = extract_template_arguments cursor;
          }
      | UnresolvedMemberExpr ->
          UnresolvedMember (ident_ref_of_cxcursor cursor)
      | _ ->
          let field = get_cursor_referenced cursor in
          let ident () = ident_ref_of_cxcursor field in
          FieldName (node ~cursor:field (Node.from_fun ident))

    and cast_of_cxcursor kind cursor =
      let operand = expr_of_cxcursor (Option.get (last_child cursor)) in
      let qual_type =
        match kind with
        | Implicit -> get_cursor_type cursor |> of_cxtype
        | _ -> ext_cursor_get_type_loc cursor |> of_type_loc in
      Cast { kind; qual_type; operand }

    and option_call_expr_of_cxcursor cursor =
      cursor |> option_cursor_bind begin fun init ->
        if get_cursor_kind init = CallExpr &&
          list_of_children init = [] then
          None
        else
          Some (expr_of_cxcursor init)
      end

    and lambda_expr_of_cxcursor cursor =
      let captures =
        list_of_iter_map lambda_capture_of_capture
          (ext_lambda_expr_get_captures cursor) in
      let parameters =
        if ext_lambda_expr_has_explicit_parameters cursor then
          Some (cursor |> list_of_children_filter_map (fun cursor ->
            if get_cursor_kind cursor = ParmDecl then
              Some (parameter_of_cxcursor cursor)
            else
              None))
        else
          None in
      let result_type =
        if ext_lambda_expr_has_explicit_result_type cursor then
          Some (
            cursor |> ext_lambda_expr_get_call_operator |>
              ext_declarator_decl_get_type_loc |>
              ext_function_type_loc_get_return_loc |> of_type_loc)
        else
          None in
      let body = stmt_of_cxcursor (Option.get (last_child cursor)) in
      Lambda {
        captures; body; parameters; result_type;
        capture_default = ext_lambda_expr_get_capture_default cursor;
        is_mutable = ext_lambda_expr_is_mutable cursor; }

    and lambda_capture_of_capture capture =
      let capture_kind = ext_lambda_capture_get_kind capture in
      let captured_var_name : string option =
        match capture_kind with
        | ByCopy | ByRef ->
            capture |> ext_lambda_capture_get_captured_var |>
            option_cursor_map get_cursor_spelling
        | This | StarThis | VLAType -> None in
      { implicit = ext_lambda_capture_is_implicit capture;
        capture_kind;
        captured_var_name;
        pack_expansion = ext_lambda_capture_is_pack_expansion capture;
      }

    and unary_expr_of_cxcursor cursor =
      let kind = cursor |> ext_unary_expr_get_kind in
      let argument =
        if cursor |> ext_unary_expr_is_argument_type then
          let qual_type =
            cursor |> ext_unary_expr_get_argument_type_loc |> of_type_loc in
          ArgumentType qual_type
        else
          match list_of_children cursor with
          | [argument] -> ArgumentExpr (argument |> expr_of_cxcursor)
          | _ -> raise Invalid_structure in
      UnaryExpr { kind; argument }

    and template_parameter_of_cxcursor cursor : template_parameter =
      match
        match get_cursor_kind cursor with
        | TemplateTypeParameter ->
            let default =
              ext_template_type_parm_decl_get_default_argument cursor in
            let default : qual_type option =
              match get_type_kind default with
              | Invalid -> None
              | _ -> Some (default |> of_cxtype) in
            Some (Class { default } : template_parameter_kind)
        | NonTypeTemplateParameter ->
            let parameter_type = get_cursor_type cursor |> of_cxtype in
            let default =
              ext_non_type_template_parm_decl_get_default_argument cursor in
            let default : expr option =
              match get_cursor_kind default with
              | InvalidCode -> None
              | _ -> Some (expr_of_cxcursor default) in
            Some (NonType { parameter_type; default })
        | TemplateTemplateParameter ->
            let parameters = extract_template_parameters cursor in
            let default : string option =
              match last_child cursor with
              | None -> None
              | Some cursor ->
                  if is_template_parameter cursor then
                    None
                  else
                    Some (get_cursor_spelling cursor) in
            Some (Template { parameters; default })
        | _ -> None
      with
      | None -> raise Invalid_structure
      | Some parameter_kind ->
          let desc () =
            let parameter_name = get_cursor_spelling cursor in
            let parameter_pack =
              ext_template_parm_is_parameter_pack cursor in
            { parameter_name; parameter_kind; parameter_pack} in
          node ~cursor (Node.from_fun desc)

    and extract_template_parameters cursor =
      extract_template_parameter_list
        (ext_template_decl_get_template_parameters cursor)

    and extract_template_parameter_list list = {
      list =
        List.init (ext_template_parameter_list_size list) begin fun i ->
          ext_template_parameter_list_get_param list i |>
          template_parameter_of_cxcursor
        end;
      requires_clause =
        ext_template_parameter_list_get_requires_clause list |>
        option_cursor_map expr_of_cxcursor;
    }

    and extract_template_arguments cursor =
      List.init (ext_cursor_get_num_template_args cursor) begin fun i ->
        ext_cursor_get_template_arg cursor i |>
        make_template_argument
      end

    and make_template ?(optional = false) cursor body =
      let parameters = extract_template_parameters cursor in
      match parameters with
      | { list = []; requires_clause = None } when optional -> body
      | _ ->
          TemplateDecl
            { parameters; decl = node ~cursor (Node.from_val body) }

    let translation_unit_of_cxcursor cursor =
      let desc () =
        let filename = get_cursor_spelling cursor in
        let items = list_of_children_map decl_of_cxcursor cursor in
        { filename; items } in
      node ~cursor (Node.from_fun desc)

    let of_cxtranslationunit tu =
      translation_unit_of_cxcursor (get_translation_unit_cursor tu)

    let rec type_loc_of_typeloc typeloc =
      let desc =
        match ext_type_loc_get_class typeloc with
        | Builtin ->
            BuiltinTypeLoc (ext_type_loc_get_type typeloc |> get_type_kind)
        | Typedef ->
            TypedefTypeLoc (
              ext_type_loc_get_type typeloc |> get_type_declaration |>
              ident_ref_of_cxcursor)
        | Pointer ->
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc typeloc |>
              type_loc_of_typeloc in
            PointerTypeLoc { pointee }
        | BlockPointer ->
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc typeloc |>
              type_loc_of_typeloc in
            BlockPointerTypeLoc { pointee }
        | MemberPointer ->
            let class_ =
              ext_member_pointer_type_loc_get_class_loc typeloc |>
              type_loc_of_typeloc in
            let pointee =
              ext_pointer_like_type_loc_get_pointee_loc typeloc |>
              type_loc_of_typeloc in
            MemberPointerTypeLoc { class_; pointee }
        | ConstantArray ->
            let size =
              ext_array_type_loc_get_size_expr typeloc |>
              expr_of_cxcursor in
            let element =
              ext_array_type_loc_get_element_loc typeloc |>
              type_loc_of_typeloc in
            ConstantArrayTypeLoc { size; element }
        | VariableArray ->
            let size =
              ext_array_type_loc_get_size_expr typeloc |>
              expr_of_cxcursor in
            let element =
              ext_array_type_loc_get_element_loc typeloc |>
              type_loc_of_typeloc in
            VariableArrayTypeLoc { size; element }
        | IncompleteArray ->
            let element =
              ext_array_type_loc_get_element_loc typeloc |>
              type_loc_of_typeloc in
            IncompleteArrayTypeLoc { element }
        | FunctionProto
        | FunctionNoProto ->
            let result =
              ext_function_type_loc_get_return_loc typeloc |>
              type_loc_of_typeloc in
            let parameters =
              List.init
                (ext_function_type_loc_get_num_params typeloc)
                (fun i ->
                  ext_function_type_loc_get_param typeloc i |>
                  parameter_of_cxcursor) in
            FunctionTypeLoc { result; parameters }
        | Paren ->
            (ext_paren_type_loc_get_inner_loc typeloc |>
            type_loc_of_typeloc).desc
        | Elaborated ->
            ElaboratedTypeLoc (
              ext_type_loc_get_type typeloc |> ext_type_get_named_type |>
              of_cxtype)
        | Record ->
            RecordTypeLoc (
              ext_type_loc_get_type typeloc |> get_type_declaration |>
              ident_ref_of_cxcursor)
        | Enum ->
            EnumTypeLoc (
              ext_type_loc_get_type typeloc |> get_type_declaration |>
              ident_ref_of_cxcursor)
        | Qualified ->
            QualifiedTypeLoc (
              ext_qualified_type_loc_get_unqualified_loc typeloc |>
              type_loc_of_typeloc)
        | c -> UnknownTypeLoc c in
      { typeloc = Some typeloc; desc }
  end

  let of_cxtype ?(options = Options.default) tu =
    let module Convert = Converter (struct let options = options end) in
    Convert.of_cxtype tu

  let of_type_loc ?(options = Options.default) tu =
    let module Convert = Converter (struct let options = options end) in
    Convert.of_type_loc tu

  let of_cxtranslationunit ?(options = Options.default) tu =
    let module Convert = Converter (struct let options = options end) in
    Convert.of_cxtranslationunit tu

  let parse_file_res ?index ?command_line_args ?unsaved_files ?clang_options
      ?options filename =
    parse_file_res ?index ?command_line_args ?unsaved_files
      ?options:clang_options filename |>
    Result.map @@ of_cxtranslationunit ?options

  let parse_file ?index ?command_line_args ?unsaved_files ?clang_options
      ?options filename =
    parse_file ?index ?command_line_args ?unsaved_files ?options:clang_options
      filename |>
    of_cxtranslationunit ?options

  let parse_string_res ?index ?filename ?command_line_args
      ?unsaved_files ?clang_options ?options string =
    parse_string_res ?index ?filename ?command_line_args
      ?unsaved_files ?options:clang_options string |>
    Result.map @@ of_cxtranslationunit ?options

  let parse_string ?index ?filename ?command_line_args ?unsaved_files
      ?clang_options ?options string =
    parse_string ?index ?filename ?command_line_args ?unsaved_files
      ?options:clang_options string |>
    of_cxtranslationunit ?options

  let to_cxtranslationunit tu =
    tu |> cursor_of_node |> cursor_get_translation_unit

  let seq_of_diagnostics tu =
    seq_of_diagnostics (tu |> to_cxtranslationunit)

  let format_diagnostics ?pp filter format tu =
    format_diagnostics ?pp filter format (tu |> to_cxtranslationunit)

  let has_severity filter tu =
    has_severity filter (tu |> to_cxtranslationunit)
end])]

module Expr = [%meta node_module [%str
  type t = Ast.expr [@@deriving refl]

  let of_cxcursor ?(options = Ast.Options.default) cur =
    let module Convert = Ast.Converter (struct let options = options end) in
    Convert.expr_of_cxcursor cur

  let get_definition e =
    e |> Ast.cursor_of_node |> get_cursor_definition

  type radix = Decimal | Octal | Hexadecimal | Binary [@@deriving refl]

  let radix_of_string s =
    if s.[0] = '0' then
      if String.length s > 1 then
        match s.[1] with
        | 'x' | 'X' -> Hexadecimal
        | 'b' | 'B' -> Binary
        | _ -> Octal
      else
        Octal
    else
      Decimal

  let radix_of_integer_literal (expr : t) : radix option =
    let tokens = Ast.tokens_of_node expr in
    (* [tokens] should be an array of length 1: however, with Clang <7,
       [tokens] include the token next to the range. *)
    if Array.length tokens >= 1 then
      Some (radix_of_string tokens.(0))
    else
      None

  let parse_string ?index ?clang_options ?options ?(filename = "<string>")
      ?(line = 1) ?(context = [])
      (s : string) : t option * Ast.translation_unit =
    let code = Format.asprintf {|
void f(void) {
  %a
#pragma clang diagnostic ignored "-Wunused-value"
#line %d "%s"
%s;
}
      |} Printer.decls context line filename s in
    let ast = Ast.parse_string ?index ?clang_options ?options code in
    let expr =
      match (Node.force ast.desc).items with
      | [{ desc; _}] ->
          begin match Node.force desc with
          | Function { body = Some { desc; _}; _} ->
              begin match Node.force desc with
              | Compound stmts ->
                  begin match List.rev stmts with
                  | { desc; _} :: _ ->
                      begin match Node.force desc with
                      | Expr e -> Some e
                      | _ -> None
                      end
                  | _ -> None
                  end
              | _ -> None
              end
          | _ -> None
          end
      | _ -> None in
    (expr, ast)
]]

module Type_loc = [%meta node_module [%str
  type t = Ast.type_loc [@@deriving refl]

  let to_qual_type ?options (t : t) =
    match t.typeloc with
    | Some tl -> Ast.of_type_loc ?options tl
    | None -> get_cursor_type (get_null_cursor ()) |> Ast.of_cxtype ?options

  let of_typeloc ?(options = Ast.Options.default) typeloc =
    let module Convert = Ast.Converter (struct let options = options end) in
    Convert.type_loc_of_typeloc typeloc
]]

module Decl = [%meta node_module [%str
  type t = Ast.decl [@@deriving refl]

  let of_cxcursor ?(options = Ast.Options.default) cur =
    let module Convert = Ast.Converter (struct let options = options end) in
    Convert.decl_of_cxcursor cur

  let get_typedef_underlying_type ?options ?(recursive = false) decl =
    let result =
      decl |> Ast.cursor_of_node |> ext_typedef_decl_get_underlying_type_loc in
    let result =
      if recursive then
        get_typedef_underlying_type_loc ~recursive:true result
      else
        result in
    Ast.of_type_loc ?options result

  let get_field_bit_width field =
    field |> Ast.cursor_of_node |> get_field_decl_bit_width

  let get_size_expr ?options decl =
    decl |> Ast.cursor_of_node |>
    ext_declarator_decl_get_size_expr |> Expr.of_cxcursor ?options

  let get_type_loc ?options decl =
    decl |> Ast.cursor_of_node |>
    ext_declarator_decl_get_type_loc |> Type_loc.of_typeloc ?options

  let get_canonical decl =
    decl |> Ast.cursor_of_node |> get_canonical_cursor

  type annotated_field = {
      specifier : Ast.cxx_access_specifier;
      decl : Ast.decl;
    }

  let annotate_access_specifier
      (default_specifier : Ast.cxx_access_specifier)
      (fields : Ast.decl list) : annotated_field list =
    let annotate_field (specifier, rev) (decl : Ast.decl) =
      match Node.force decl.desc with
      | AccessSpecifier specifier -> (specifier, rev)
      | _ -> (specifier, { specifier; decl } :: rev) in
    let _specifier, rev =
      List.fold_left annotate_field (default_specifier, []) fields in
    List.rev rev
]]

module Parameter = [%meta node_module [%str
  type t = Ast.parameter [@@deriving refl]

  let get_size_expr ?options param =
    param |> Ast.cursor_of_node |>
    ext_declarator_decl_get_size_expr |> Expr.of_cxcursor ?options

  let get_type_loc ?options param =
    param |> Ast.cursor_of_node |>
    ext_declarator_decl_get_type_loc |> Type_loc.of_typeloc ?options
]]

module Type = [%meta node_module [%str
  type t = Ast.qual_type [@@deriving refl]

  let make ?(const = false) ?(volatile = false) ?(restrict = false) desc : t =
    { cxtype = get_cursor_type (get_null_cursor ()); type_loc = None;
      const; volatile; restrict; desc }

  let of_cxtype = Ast.of_cxtype

  let of_type_loc = Ast.of_type_loc

  let of_cursor ?options cursor =
    get_cursor_type cursor |> of_cxtype ?options

  let of_decoration ?options (decoration : Ast.decoration) =
    match decoration with
    | Cursor cursor -> of_cursor ?options cursor
    | Custom { qual_type; _ } ->
        match qual_type with
        | Some qual_type -> qual_type
        | None -> invalid_arg "of_decoration"

  let of_node ?options (node : 'a Ast.node) =
    of_decoration ?options node.decoration

  let get_size_of (ty : t) = type_get_size_of ty.cxtype

  let get_align_of (ty : t) = type_get_align_of ty.cxtype

  let get_offset_of (ty : t) (field_name : string) =
    let cxtype = get_typedef_underlying_type ~recursive:true ty.cxtype in
    let result = type_get_offset_of cxtype field_name in
    if result = -1 then
      invalid_arg "Clang.Type.get_offset_of"
    else
      result

  let get_typedef_underlying_type ?options ?recursive (qual_type : t) =
    get_typedef_underlying_type ?recursive qual_type.cxtype |>
    of_cxtype ?options

  let get_declaration ?options (qual_type : t) =
    get_type_declaration qual_type.cxtype |> Decl.of_cxcursor ?options

  let iter_fields ?options f (qual_type : t) =
    qual_type.cxtype |> iter_type_fields @@ fun x ->
      f (Decl.of_cxcursor ?options x)

  let list_of_fields ?options (qual_type : t) =
    qual_type.cxtype |> list_of_type_fields |> List.map @@
      Decl.of_cxcursor ?options
]]

module Stmt = [%meta node_module [%str
  type t = Ast.stmt [@@deriving refl]

  let of_cxcursor ?(options = Ast.Options.default) cur =
    let module Convert = Ast.Converter (struct let options = options end) in
    Convert.stmt_of_cxcursor cur
]]

module Enum_constant = [%meta node_module [%str
  type t = Ast.enum_constant [@@deriving refl]

  let of_cxcursor ?(options = Ast.Options.default) cur =
    let module Convert = Ast.Converter (struct let options = options end) in
    Convert.enum_constant_of_cxcursor cur

  let get_value enum_constant =
    enum_constant |> Ast.cursor_of_node |> get_enum_constant_decl_value
]]

module Translation_unit = [%meta node_module [%str
  type t = Ast.translation_unit [@@deriving refl]

  let make ?(filename = "") items : Ast.translation_unit_desc =
    { filename; items }
]]
end

module Id = Custom (Clang__ast.IdNode)

module Lazy = Custom (Clang__ast.LazyNode)

include Id