Welcome to mirror list, hosted at ThFree Co, Russian Federation.

parser.c - github.com/facebook/luaffifb.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: dceb84550b63e194333757effb368b6d7fd15078 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
/* vim: ts=4 sw=4 sts=4 et tw=78
 * Portions copyright (c) 2015-present, Facebook, Inc. All rights reserved.
 * Portions copyright (c) 2011 James R. McKaskill.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
#include "ffi.h"

#define IS_CONST(tok) (IS_LITERAL(tok, "const") || IS_LITERAL(tok, "__const") || IS_LITERAL(tok, "__const__"))
#define IS_VOLATILE(tok) (IS_LITERAL(tok, "volatile") || IS_LITERAL(tok, "__volatile") || IS_LITERAL(tok, "__volatile__"))
#define IS_RESTRICT(tok) (IS_LITERAL(tok, "restrict") || IS_LITERAL(tok, "__restrict") || IS_LITERAL(tok, "__restrict__"))
#define IS_INLINE(tok) (IS_LITERAL(tok, "inline") || IS_LITERAL(tok, "__inline") || IS_LITERAL(tok, "__inline__"))

enum etoken {
    TOK_NIL,
    TOK_NUMBER,
    TOK_STRING,
    TOK_TOKEN,

    /* the order of these values must match the token strings in lex.c */

    TOK_3_BEGIN,
    TOK_VA_ARG,

    TOK_2_BEGIN,
    TOK_LEFT_SHIFT, TOK_RIGHT_SHIFT, TOK_LOGICAL_AND, TOK_LOGICAL_OR, TOK_LESS_EQUAL,
    TOK_GREATER_EQUAL, TOK_EQUAL, TOK_NOT_EQUAL,

    TOK_1_BEGIN,
    TOK_OPEN_CURLY, TOK_CLOSE_CURLY, TOK_SEMICOLON, TOK_COMMA, TOK_COLON,
    TOK_ASSIGN, TOK_OPEN_PAREN, TOK_CLOSE_PAREN, TOK_OPEN_SQUARE, TOK_CLOSE_SQUARE,
    TOK_DOT, TOK_AMPERSAND, TOK_LOGICAL_NOT, TOK_BITWISE_NOT, TOK_MINUS,
    TOK_PLUS, TOK_STAR, TOK_DIVIDE, TOK_MODULUS, TOK_LESS,
    TOK_GREATER, TOK_BITWISE_XOR, TOK_BITWISE_OR, TOK_QUESTION, TOK_POUND,

    TOK_REFERENCE = TOK_AMPERSAND,
    TOK_MULTIPLY = TOK_STAR,
    TOK_BITWISE_AND = TOK_AMPERSAND,
};

struct token {
    enum etoken type;
    int64_t integer;
    const char* str;
    size_t size;
};

#define IS_LITERAL(TOK, STR) \
  (((TOK).size == sizeof(STR) - 1) && 0 == memcmp((TOK).str, STR, sizeof(STR) - 1))

/* the order of tokens _must_ match the order of the enum etoken enum */

static char tok3[][4] = {
    "...", /* unused ">>=", "<<=", */
};

static char tok2[][3] = {
    "<<", ">>", "&&", "||", "<=",
    ">=", "==", "!=",
    /* unused "+=", "-=", "*=", "/=", "%=", "&=", "^=", "|=", "++", "--", "->", "::", */
};

static char tok1[] = {
    '{', '}', ';', ',', ':',
    '=', '(', ')', '[', ']',
    '.', '&', '!', '~', '-',
    '+', '*', '/', '%', '<',
    '>', '^', '|', '?', '#'
};

static int next_token(lua_State* L, struct parser* P, struct token* tok)
{
    size_t i;
    const char* s = P->next;

    /* UTF8 BOM */
    if (s[0] == '\xEF' && s[1] == '\xBB' && s[2] == '\xBF') {
        s += 3;
    }

    /* consume whitespace and comments */
    for (;;) {
        /* consume whitespace */
        while(*s == '\t' || *s == '\n' || *s == ' ' || *s == '\v' || *s == '\r') {
            if (*s == '\n') {
                P->line++;
            }
            s++;
        }

        /* consume comments */
        if (*s == '/' && *(s+1) == '/') {

            s = strchr(s, '\n');
            if (!s) {
                luaL_error(L, "non-terminated comment");
            }

        } else if (*s == '/' && *(s+1) == '*') {
            s += 2;

            for (;;) {
                if (s[0] == '\0') {
                    luaL_error(L, "non-terminated comment");
                } else if (s[0] == '*' && s[1] == '/') {
                    s += 2;
                    break;
                } else if (s[0] == '\n') {
                    P->line++;
                }
                s++;
            }

        } else if (*s == '\0') {
            tok->type = TOK_NIL;
            return 0;

        } else {
            break;
        }
    }

    P->prev = s;

    for (i = 0; i < sizeof(tok3) / sizeof(tok3[0]); i++) {
        if (s[0] == tok3[i][0] && s[1] == tok3[i][1] && s[2] == tok3[i][2]) {
            tok->type = (enum etoken) (TOK_3_BEGIN + 1 + i);
            P->next = s + 3;
            goto end;
        }
    }

    for (i = 0; i < sizeof(tok2) / sizeof(tok2[0]); i++) {
        if (s[0] == tok2[i][0] && s[1] == tok2[i][1]) {
            tok->type = (enum etoken) (TOK_2_BEGIN + 1 + i);
            P->next = s + 2;
            goto end;
        }
    }

    for (i = 0; i < sizeof(tok1) / sizeof(tok1[0]); i++) {
        if (s[0] == tok1[i]) {
            tok->type = (enum etoken) (TOK_1_BEGIN + 1 + i);
            P->next = s + 1;
            goto end;
        }
    }

    if (*s == '.' || *s == '-' || ('0' <= *s && *s <= '9')) {
        /* number */
        tok->type = TOK_NUMBER;

        /* split out the negative case so we get the full range of bits for
         * unsigned (eg to support 0xFFFFFFFF where sizeof(long) == 4)
         */
        if (*s == '-') {
            tok->integer = strtol(s, (char**) &s, 0);
        } else {
            tok->integer = strtoul(s, (char**) &s, 0);
        }

        while (*s == 'u' || *s == 'U' || *s == 'l' || *s == 'L') {
            s++;
        }

        P->next = s;
        goto end;

    } else if (*s == '\'' || *s == '\"') {
        /* "..." or '...' */
        char quote = *s;
        s++; /* jump over " */

        tok->type = TOK_STRING;
        tok->str = s;

        while (*s != quote) {

            if (*s == '\0' || (*s == '\\' && *(s+1) == '\0')) {
                return luaL_error(L, "string not finished");
            }

            if (*s == '\\') {
                s++;
            }

            s++;
        }

        tok->size = s - tok->str;
        s++; /* jump over " */
        P->next = s;
        goto end;

    } else if (('a' <= *s && *s <= 'z') || ('A' <= *s && *s <= 'Z') || *s == '_') {
        /* tokens */
        tok->type = TOK_TOKEN;
        tok->str = s;

        while (('a' <= *s && *s <= 'z') || ('A' <= *s && *s <= 'Z') || *s == '_' || ('0' <= *s && *s <= '9')) {
            s++;
        }

        tok->size = s - tok->str;
        P->next = s;
        goto end;

    } else {
        return luaL_error(L, "invalid character %d", P->line);
    }

end:
    /*fprintf(stderr, "token %d %d %.*s %.10s\n", tok->type, (int) tok->size, (tok->type == TOK_TOKEN || tok->type == TOK_STRING) ? (int) tok->size : 0, tok->str, P->next);*/
    return 1;
}

#define require_token(L, P, tok) require_token_line(L, P, tok, __FILE__, __LINE__)

static void require_token_line(lua_State* L, struct parser* P, struct token* tok, const char* file, int line)
{
    if (!next_token(L, P, tok)) {
        luaL_error(L, "unexpected end on line %s:%d", file, line);
    }
}

static void check_token(lua_State* L, struct parser* P, int type, const char* str, const char* err, ...)
{
    struct token tok;
    if (!next_token(L, P, &tok) || tok.type != type || (tok.type == TOK_TOKEN && (tok.size != strlen(str) || memcmp(tok.str, str, tok.size) != 0))) {
        va_list ap;
        va_start(ap, err);
        lua_pushvfstring(L, err, ap);
        lua_error(L);
    }
}

static void put_back(struct parser* P)
{ P->next = P->prev; }


int64_t calculate_constant(lua_State* L, struct parser* P);

static int g_name_key;
static int g_front_name_key;
static int g_back_name_key;

#ifndef max
#define max(a,b) ((a) < (b) ? (b) : (a))
#endif

#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif

enum test {TEST};

/* Parses an enum definition from after the open curly through to the close
 * curly. Expects the user table to be on the top of the stack
 */
static int parse_enum(lua_State* L, struct parser* P, struct ctype* type)
{
    struct token tok;
    int value = -1;
    int ct_usr = lua_gettop(L);

    for (;;) {
        require_token(L, P, &tok);

        assert(lua_gettop(L) == ct_usr);

        if (tok.type == TOK_CLOSE_CURLY) {
            break;
        } else if (tok.type != TOK_TOKEN) {
            return luaL_error(L, "unexpected token in enum at line %d", P->line);
        }

        lua_pushlstring(L, tok.str, tok.size);

        require_token(L, P, &tok);

        if (tok.type == TOK_COMMA || tok.type == TOK_CLOSE_CURLY) {
            /* we have an auto calculated enum value */
            value++;
        } else if (tok.type == TOK_ASSIGN) {
            /* we have an explicit enum value */
            value = (int) calculate_constant(L, P);
            require_token(L, P, &tok);
        } else {
            return luaL_error(L, "unexpected token in enum at line %d", P->line);
        }

        assert(lua_gettop(L) == ct_usr + 1);

        /* add the enum value to the constants table */
        push_upval(L, &constants_key);
        lua_pushvalue(L, -2);
        lua_pushinteger(L, value);
        lua_rawset(L, -3);
        lua_pop(L, 1);

        assert(lua_gettop(L) == ct_usr + 1);

        /* add the enum value to the enum usr value table */
        lua_pushinteger(L, value);
        lua_rawset(L, ct_usr);

        if (tok.type == TOK_CLOSE_CURLY) {
            break;
        } else if (tok.type != TOK_COMMA) {
            return luaL_error(L, "unexpected token in enum at line %d", P->line);
        }
    }

    type->base_size = sizeof(enum test);
    type->align_mask = sizeof(enum test) - 1;

    assert(lua_gettop(L) == ct_usr);
    return 0;
}

static void calculate_member_position(lua_State* L, struct parser* P, struct ctype* ct, struct ctype* mt, int* pbit_offset, int* pbitfield_type)
{
    int bit_offset = *pbit_offset;

    if (ct->type == UNION_TYPE) {
        size_t msize;

        if (mt->is_variable_struct || mt->is_variable_array) {
            luaL_error(L, "NYI: variable sized members in unions");
            return;

        } else if (mt->is_bitfield) {
            msize = (mt->align_mask + 1);
#ifdef _WIN32
            /* MSVC has a bug where it doesn't update the alignment of
             * a union for bitfield members. */
            mt->align_mask = 0;
#endif

        } else if (mt->is_array) {
            msize = mt->array_size * (mt->pointers > 1 ? sizeof(void*) : mt->base_size);

        } else {
            msize = mt->pointers ? sizeof(void*) : mt->base_size;
        }

        ct->base_size = max(ct->base_size, msize);

    } else if (mt->is_bitfield) {
        if (mt->has_member_name && mt->bit_size == 0) {
            luaL_error(L, "zero length bitfields must be unnamed on line %d", P->line);
        }

#if defined _WIN32
        /* MSVC uses a seperate storage unit for each size. This is aligned
         * before the first bitfield. :0 finishes up the storage unit using
         * the greater alignment of the storage unit or the type used with the
         * :0. This is equivalent to the :0 always creating a new storage
         * unit, but not necesserily using it yet.
         */

        if (*pbitfield_type == -1 && mt->bit_size == 0) {
            /* :0 not after a bitfield are ignored */
            return;
        }

        {
            int different_storage = mt->align_mask != *pbitfield_type;
            int no_room_left = bit_offset + mt->bit_size > (mt->align_mask + 1) * CHAR_BIT;

            if (different_storage || no_room_left || !mt->bit_size) {
                ct->base_size += (bit_offset + CHAR_BIT - 1) / CHAR_BIT;
                bit_offset = 0;
                if (*pbitfield_type >= 0) {
                    ct->base_size = ALIGN_UP(ct->base_size, *pbitfield_type);
                }
                ct->base_size = ALIGN_UP(ct->base_size, mt->align_mask);
            }
        }

        mt->bit_offset = bit_offset;
        mt->offset = ct->base_size;

        *pbitfield_type = mt->align_mask;
        bit_offset += mt->bit_size;

// #elif defined OS_OSX
//         /* OSX doesn't use containers and bitfields are not aligned. So
//          * bitfields never add any padding, except for :0 which still forces
//          * an alignment based off the type used with the :0 */
//         if (mt->bit_size) {
//             mt->offset = ct->base_size;
//             mt->bit_offset = bit_offset;
//             bit_offset += mt->bit_size;
//             ct->base_size += bit_offset / CHAR_BIT;
//             bit_offset = bit_offset % CHAR_BIT;
//         } else {
//             ct->base_size += (bit_offset + CHAR_BIT - 1) / CHAR_BIT;
//             ct->base_size = ALIGN_UP(ct->base_size, mt->align_mask);
//             bit_offset = 0;
//         }

//         if (!mt->has_member_name) {
//             /* unnamed bitfields don't update the struct alignment */
//             mt->align_mask = 0;
//         }

#elif defined __GNUC__
        /* GCC tries to pack bitfields in as close as much as possible, but
         * still making sure that they don't cross alignment boundaries.
         * :0 forces an alignment based off the type used with the :0
         */

        int bits_used = (ct->base_size - ALIGN_DOWN(ct->base_size, mt->align_mask)) * CHAR_BIT + bit_offset;
        int need_to_realign = bits_used + mt->bit_size > mt->base_size * CHAR_BIT;

        if (!mt->is_packed && (!mt->bit_size || need_to_realign)) {
            ct->base_size += (bit_offset + CHAR_BIT - 1) / CHAR_BIT;
            ct->base_size = ALIGN_UP(ct->base_size, mt->align_mask);
            bit_offset = 0;
        }

        mt->bit_offset = bit_offset;
        mt->offset = ct->base_size;

        bit_offset += mt->bit_size;
        ct->base_size += bit_offset / CHAR_BIT;
        bit_offset = bit_offset % CHAR_BIT;

        /* unnamed bitfields don't update the struct alignment */
        if (!mt->has_member_name) {
            mt->align_mask = 0;
        }
#else
#error
#endif

    } else {
        /* finish up the current bitfield storage unit */
        ct->base_size += (bit_offset + CHAR_BIT - 1) / CHAR_BIT;
        bit_offset = 0;

        if (*pbitfield_type >= 0) {
            ct->base_size = ALIGN_UP(ct->base_size, *pbitfield_type);
        }

        *pbitfield_type = -1;

        ct->base_size = ALIGN_UP(ct->base_size, mt->align_mask);
        mt->offset = ct->base_size;

        if (mt->is_variable_array) {
            ct->is_variable_struct = 1;
            ct->variable_increment = mt->pointers > 1 ? sizeof(void*) : mt->base_size;

        } else if (mt->is_variable_struct) {
            assert(!mt->variable_size_known && !mt->is_array && !mt->pointers);
            ct->base_size += mt->base_size;
            ct->is_variable_struct = 1;
            ct->variable_increment = mt->variable_increment;

        } else if (mt->is_array) {
            ct->base_size += mt->array_size * (mt->pointers > 1 ? sizeof(void*) : mt->base_size);

        } else {
            ct->base_size += mt->pointers ? sizeof(void*) : mt->base_size;
        }
    }

    /* increase the outer struct/union alignment if needed */
    if (mt->align_mask > (int) ct->align_mask) {
        ct->align_mask = mt->align_mask;
    }

    if (mt->has_bitfield || mt->is_bitfield) {
        ct->has_bitfield = 1;
    }

    *pbit_offset = bit_offset;
}

static int copy_submembers(lua_State* L, int to_usr, int from_usr, const struct ctype* ft, int* midx)
{
    struct ctype ct;
    int i, sublen;

    from_usr = lua_absindex(L, from_usr);
    to_usr = lua_absindex(L, to_usr);

    /* integer keys */
    sublen = (int) lua_rawlen(L, from_usr);
    for (i = 1; i <= sublen; i++) {
        lua_rawgeti(L, from_usr, i);

        ct = *(const struct ctype*) lua_touserdata(L, -1);
        ct.offset += ft->offset;
        lua_getuservalue(L, -1);

        push_ctype(L, -1, &ct);
        lua_rawseti(L, to_usr, (*midx)++);

        lua_pop(L, 2); /* ctype, user value */
    }

    /* string keys */
    lua_pushnil(L);
    while (lua_next(L, from_usr)) {
        if (lua_type(L, -2) == LUA_TSTRING) {
            struct ctype ct = *(const struct ctype*) lua_touserdata(L, -1);
            ct.offset += ft->offset;
            lua_getuservalue(L, -1);

            /* uservalue[sub_mname] = new_sub_mtype */
            lua_pushvalue(L, -3);
            push_ctype(L, -2, &ct);
            lua_rawset(L, to_usr);

            lua_pop(L, 1); /* remove submember user value */
        }
        lua_pop(L, 1);
    }

    return 0;
}

static int add_member(lua_State* L, int ct_usr, int mname, int mbr_usr, const struct ctype* mt, int* midx)
{
    ct_usr = lua_absindex(L, ct_usr);
    mname = lua_absindex(L, mname);

    push_ctype(L, mbr_usr, mt);

    /* usrvalue[mbr index] = pushed mtype */
    lua_pushvalue(L, -1);
    lua_rawseti(L, ct_usr, (*midx)++);

    /* set usrvalue[mname] = pushed mtype */
    lua_pushvalue(L, mname);
    lua_pushvalue(L, -2);
    lua_rawset(L, ct_usr);

    /* set usrvalue[mtype] = mname */
    lua_pushvalue(L, -1);
    lua_pushvalue(L, mname);
    lua_rawset(L, ct_usr);

    lua_pop(L, 1);

    return 0;
}

/* Parses a struct from after the open curly through to the close curly.
 */
static int parse_struct(lua_State* L, struct parser* P, int tmp_usr, const struct ctype* ct)
{
    struct token tok;
    int midx = 1;
    int top = lua_gettop(L);

    tmp_usr = lua_absindex(L, tmp_usr);

    /* parse members */
    for (;;) {
        struct ctype mbase;

        assert(lua_gettop(L) == top);

        /* see if we're at the end of the struct */
        require_token(L, P, &tok);
        if (tok.type == TOK_CLOSE_CURLY) {
            break;
        } else if (ct->is_variable_struct) {
            return luaL_error(L, "can't have members after a variable sized member on line %d", P->line);
        } else {
            put_back(P);
        }

        /* members are of the form
         * <base type> <arg>, <arg>, <arg>;
         * eg struct foo bar, *bar2[2];
         * mbase is 'struct foo'
         * mtype is '' then '*[2]'
         * mname is 'bar' then 'bar2'
         */

        parse_type(L, P, &mbase);

        for (;;) {
            struct token mname;
            struct ctype mt = mbase;

            memset(&mname, 0, sizeof(mname));

            if (ct->is_variable_struct) {
                return luaL_error(L, "can't have members after a variable sized member on line %d", P->line);
            }

            assert(lua_gettop(L) == top + 1);
            parse_argument(L, P, -1, &mt, &mname, NULL);
            assert(lua_gettop(L) == top + 2);

            if (!mt.is_defined && (mt.pointers - mt.is_array) == 0) {
                return luaL_error(L, "member type is undefined on line %d", P->line);
            }

            if (mt.type == VOID_TYPE && (mt.pointers - mt.is_array) == 0) {
                return luaL_error(L, "member type can not be void on line %d", P->line);
            }

            mt.has_member_name = (mname.size > 0);
            lua_pushlstring(L, mname.str, mname.size);

            add_member(L, tmp_usr, -1, -2, &mt, &midx);

            /* pop the usr value from push_argument and the member name */
            lua_pop(L, 2);
            assert(lua_gettop(L) == top + 1);

            require_token(L, P, &tok);
            if (tok.type == TOK_SEMICOLON) {
                break;
            } else if (tok.type != TOK_COMMA) {
                luaL_error(L, "unexpected token in struct definition on line %d", P->line);
            }
        }

        /* pop the usr value from push_type */
        lua_pop(L, 1);
    }

    assert(lua_gettop(L) == top);
    return 0;
}

static int calculate_struct_offsets(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct, int tmp_usr)
{
    int i;
    int midx = 1;
    int sz = (int) lua_rawlen(L, tmp_usr);
    int bit_offset = 0;
    int bitfield_type = -1;

    ct_usr = lua_absindex(L, ct_usr);
    tmp_usr = lua_absindex(L, tmp_usr);

    for (i = 1; i <= sz; i++) {
        struct ctype mt;

        /* get the member type */
        lua_rawgeti(L, tmp_usr, i);
        mt = *(const struct ctype*) lua_touserdata(L, -1);

        /* get the member user table */
        lua_getuservalue(L, -1);

        /* get the member name */
        lua_pushvalue(L, -2);
        lua_rawget(L, tmp_usr);

        calculate_member_position(L, P, ct, &mt, &bit_offset, &bitfield_type);

        if (mt.has_member_name) {
            assert(!lua_isnil(L, -1));
            add_member(L, ct_usr, -1, -2, &mt, &midx);

        } else if (mt.type == STRUCT_TYPE || mt.type == UNION_TYPE) {
            /* With an unnamed member we copy all of the submembers into our
             * usr value adjusting the offset as necessary. Note ctypes are
             * immutable so need to push a new ctype to update the offset.
             */
            copy_submembers(L, ct_usr, -2, &mt, &midx);

        } else {
            /* We ignore unnamed members that aren't structs or unions. These
             * are there just to change the padding */
        }

        lua_pop(L, 3);
    }

    /* finish up the current bitfield storage unit */
    ct->base_size += (bit_offset + CHAR_BIT - 1) / CHAR_BIT;

    /* only void is allowed 0 size */
    if (ct->base_size == 0) {
        ct->base_size = 1;
    }

    ct->base_size = ALIGN_UP(ct->base_size, ct->align_mask);
    return 0;
}

/* copy over attributes that could be specified before the typedef eg
 * __attribute__(packed) const type_t */
static void instantiate_typedef(struct parser* P, struct ctype* tt, const struct ctype* ft)
{
    struct ctype pt = *tt;
    *tt = *ft;

    tt->const_mask |= pt.const_mask;
    tt->is_packed = pt.is_packed;

    if (tt->is_packed) {
        tt->align_mask = 0;
    } else {
        /* Instantiate the typedef in the current packing. This may be
         * further updated if a pointer is added or another alignment
         * attribute is applied. If pt.align_mask is already non-zero than an
         * increased alignment via __declspec(aligned(#)) has been set. */
        tt->align_mask = max(min(P->align_mask, tt->align_mask), pt.align_mask);
    }
}

/* this parses a struct or union starting with the optional
 * name before the opening brace
 * leaves the type usr value on the stack
 */
static int parse_record(lua_State* L, struct parser* P, struct ctype* ct)
{
    struct token tok;
    int top = lua_gettop(L);

    require_token(L, P, &tok);

    /* name is optional */
    if (tok.type == TOK_TOKEN) {
        /* declaration */
        lua_pushlstring(L, tok.str, tok.size);

        assert(lua_gettop(L) == top+1);

        /* lookup the name to see if we've seen this type before */
        push_upval(L, &types_key);
        lua_pushvalue(L, -2);
        lua_rawget(L, top+2);

        assert(lua_gettop(L) == top+3);

        if (lua_isnil(L, -1)) {
            lua_pop(L, 1); /* pop the nil usr value */
            lua_newtable(L); /* the new usr table */

            /* stack layout is:
             * top+1: record name
             * top+2: types table
             * top+3: new usr table
             */

            lua_pushlightuserdata(L, &g_name_key);
            lua_pushvalue(L, top+1);
            lua_rawset(L, top+3); /* usr[name_key] = name */

            lua_pushvalue(L, top+1);
            push_ctype(L, top+3, ct);
            lua_rawset(L, top+2); /* types[name] = new_ctype */

        } else {
            /* get the exsting declared type */
            const struct ctype* prevt = (const struct ctype*) lua_touserdata(L, top+3);

            if (prevt->type != ct->type) {
                lua_getuservalue(L, top+3);
                push_type_name(L, -1, ct);
                push_type_name(L, top+3, prevt);
                luaL_error(L, "type '%s' previously declared as '%s'", lua_tostring(L, -2), lua_tostring(L, -1));
            }

            instantiate_typedef(P, ct, prevt);

            /* replace the ctype with its usr value */
            lua_getuservalue(L, -1);
            lua_replace(L, -2);
        }

        /* remove the extra name and types table */
        lua_replace(L, -3);
        lua_pop(L, 1);

        assert(lua_gettop(L) == top + 1 && lua_istable(L, -1));

        /* if a name is given then we may be at the end of the string
         * eg for ffi.new('struct foo')
         */
        if (!next_token(L, P, &tok)) {
            return 0;
        }

    } else {
        /* create a new unnamed record */
        int num;

        /* get the next unnamed number */
        push_upval(L, &next_unnamed_key);
        num = lua_tointeger(L, -1);
        lua_pop(L, 1);

        /* increment the unnamed upval */
        lua_pushinteger(L, num + 1);
        set_upval(L, &next_unnamed_key);

        lua_newtable(L); /* the new usr table - leave on stack */

        /* usr[name_key] = num */
        lua_pushlightuserdata(L, &g_name_key);
        lua_pushfstring(L, "%d", num);
        lua_rawset(L, -3);
    }

    if (tok.type != TOK_OPEN_CURLY) {
        /* this may just be a declaration or use of the type as an argument or
         * member */
        put_back(P);
        return 0;
    }

    if (ct->is_defined) {
        return luaL_error(L, "redefinition in line %d", P->line);
    }

    assert(lua_gettop(L) == top + 1 && lua_istable(L, -1));

    if (ct->type == ENUM_TYPE) {
        parse_enum(L, P, ct);
    } else {
        /* we do a two stage parse, where we parse the content first and build up
         * the temp user table. We then iterate over that to calculate the offsets
         * and fill out ct_usr. This is so we can handle out of order members
         * (eg vtable) and attributes specified at the end of the struct.
         */
        lua_newtable(L);
        parse_struct(L, P, -1, ct);
        calculate_struct_offsets(L, P, -2, ct, -1);
        assert(lua_gettop(L) == top + 2 && lua_istable(L, -1));
        lua_pop(L, 1);
    }

    assert(lua_gettop(L) == top + 1 && lua_istable(L, -1));
    set_defined(L, -1, ct);
    assert(lua_gettop(L) == top + 1);
    return 0;
}

/* parses single or multi work built in types, and pushes it onto the stack */
static int parse_type_name(lua_State* L, struct parser* P)
{
    struct token tok;
    int flags = 0;

    enum {
        UNSIGNED = 0x01,
        SIGNED = 0x02,
        LONG = 0x04,
        SHORT = 0x08,
        INT = 0x10,
        CHAR = 0x20,
        LONG_LONG = 0x40,
        INT8 = 0x80,
        INT16 = 0x100,
        INT32 = 0x200,
        INT64 = 0x400,
        DOUBLE = 0x800,
        FLOAT = 0x1000,
        COMPLEX = 0x2000,
    };

    require_token(L, P, &tok);

    /* we have to manually decode the builtin types since they can take up
     * more then one token
     */
    for (;;) {
        if (tok.type != TOK_TOKEN) {
            break;
        } else if (IS_LITERAL(tok, "unsigned")) {
            flags |= UNSIGNED;
        } else if (IS_LITERAL(tok, "signed")) {
            flags |= SIGNED;
        } else if (IS_LITERAL(tok, "short")) {
            flags |= SHORT;
        } else if (IS_LITERAL(tok, "char")) {
            flags |= CHAR;
        } else if (IS_LITERAL(tok, "long")) {
            flags |= (flags & LONG) ? LONG_LONG : LONG;
        } else if (IS_LITERAL(tok, "int")) {
            flags |= INT;
        } else if (IS_LITERAL(tok, "__int8")) {
            flags |= INT8;
        } else if (IS_LITERAL(tok, "__int16")) {
            flags |= INT16;
        } else if (IS_LITERAL(tok, "__int32")) {
            flags |= INT32;
        } else if (IS_LITERAL(tok, "__int64")) {
            flags |= INT64;
        } else if (IS_LITERAL(tok, "double")) {
            flags |= DOUBLE;
        } else if (IS_LITERAL(tok, "float")) {
            flags |= FLOAT;
        } else if (IS_LITERAL(tok, "complex") || IS_LITERAL(tok, "_Complex")) {
            flags |= COMPLEX;
        } else if (IS_LITERAL(tok, "register")) {
            /* ignore */
        } else {
            break;
        }

        if (!next_token(L, P, &tok)) {
            break;
        }
    }

    if (flags) {
        put_back(P);
    }

    if (flags & CHAR) {
        if (flags & SIGNED) {
            lua_pushliteral(L, "int8_t");
        } else if (flags & UNSIGNED) {
            lua_pushliteral(L, "uint8_t");
        } else {
            lua_pushstring(L, (((char) -1) > 0) ? "uint8_t" : "int8_t");
        }

    } else if (flags & INT8) {
        lua_pushstring(L, (flags & UNSIGNED) ? "uint8_t" : "int8_t");
    } else if (flags & INT16) {
        lua_pushstring(L, (flags & UNSIGNED) ? "uint16_t" : "int16_t");
    } else if (flags & INT32) {
        lua_pushstring(L, (flags & UNSIGNED) ? "uint32_t" : "int32_t");
    } else if (flags & (INT64 | LONG_LONG)) {
        lua_pushstring(L, (flags & UNSIGNED) ? "uint64_t" : "int64_t");

    } else if (flags & COMPLEX) {
        if (flags & LONG) {
            lua_pushliteral(L, "complex long double");
        } else if (flags & FLOAT) {
            lua_pushliteral(L, "complex float");
        } else {
            lua_pushliteral(L, "complex double");
        }

    } else if (flags & DOUBLE) {
        if (flags & LONG) {
            lua_pushliteral(L, "long double");
        } else {
            lua_pushliteral(L, "double");
        }

    } else if (flags & FLOAT) {
        lua_pushliteral(L, "float");

    } else if (flags & SHORT) {
#define SHORT_TYPE(u) (sizeof(short) == sizeof(int64_t) ? u "int64_t" : sizeof(short) == sizeof(int32_t) ? u "int32_t" : u "int16_t")
        if (flags & UNSIGNED) {
            lua_pushstring(L, SHORT_TYPE("u"));
        } else {
            lua_pushstring(L, SHORT_TYPE(""));
        }
#undef SHORT_TYPE

    } else if (flags & LONG) {
#define LONG_TYPE(u) (sizeof(long) == sizeof(int64_t) ? u "int64_t" : u "int32_t")
        if (flags & UNSIGNED) {
            lua_pushstring(L, LONG_TYPE("u"));
        } else {
            lua_pushstring(L, LONG_TYPE(""));
        }
#undef LONG_TYPE

    } else if (flags) {
#define INT_TYPE(u) (sizeof(int) == sizeof(int64_t) ? u "int64_t" : sizeof(int) == sizeof(int32_t) ? u "int32_t" : u "int16_t")
        if (flags & UNSIGNED) {
            lua_pushstring(L, INT_TYPE("u"));
        } else {
            lua_pushstring(L, INT_TYPE(""));
        }
#undef INT_TYPE

    } else {
        lua_pushlstring(L, tok.str, tok.size);
    }

    return 0;
}

/* parse_attribute parses a token to see if it is an attribute. It may then
 * parse some following tokens to decode the attribute setting the appropriate
 * fields in ct. It will return 1 if the token was used (and possibly some
 * more following it) or 0 if not. If the token was used, the next token must
 * be retrieved using next_token/require_token.
 */
static int parse_attribute(lua_State* L, struct parser* P, struct token* tok, struct ctype* ct, struct parser* asmname)
{
    if (tok->type != TOK_TOKEN) {
        return 0;

    } else if (asmname && (IS_LITERAL(*tok, "__asm__") || IS_LITERAL(*tok, "__asm"))) {
        check_token(L, P, TOK_OPEN_PAREN, NULL, "unexpected token after __asm__ on line %d", P->line);
        *asmname = *P;

        require_token(L, P, tok);
        while (tok->type == TOK_STRING) {
            require_token(L, P, tok);
        }

        if (tok->type != TOK_CLOSE_PAREN) {
            luaL_error(L, "unexpected token after __asm__ on line %d", P->line);
        }
        return 1;

    } else if (IS_LITERAL(*tok, "__attribute__") || IS_LITERAL(*tok, "__declspec")) {
        int parens = 1;
        check_token(L, P, TOK_OPEN_PAREN, NULL, "expected parenthesis after __attribute__ or __declspec on line %d", P->line);

        for (;;) {
            require_token(L, P, tok);
            if (tok->type == TOK_OPEN_PAREN) {
                parens++;
            } else if (tok->type == TOK_CLOSE_PAREN) {
                if (--parens == 0) {
                    break;
                }

            } else if (tok->type != TOK_TOKEN) {
                /* ignore unknown symbols within parentheses */

            } else if (IS_LITERAL(*tok, "align") || IS_LITERAL(*tok, "aligned") || IS_LITERAL(*tok, "__aligned__")) {
                unsigned align = 0;
                require_token(L, P, tok);

                switch (tok->type) {
                case TOK_CLOSE_PAREN:
                    align = ALIGNED_DEFAULT;
                    put_back(P);
                    break;

                case TOK_OPEN_PAREN:
                    require_token(L, P, tok);

                    if (tok->type != TOK_NUMBER) {
                        luaL_error(L, "expected align(#) on line %d", P->line);
                    }

                    switch (tok->integer) {
                    case 1: align = 0; break;
                    case 2: align = 1; break;
                    case 4: align = 3; break;
                    case 8: align = 7; break;
                    case 16: align = 15; break;
                    default:
                        luaL_error(L, "unsupported align size on line %d", P->line);
                    }

                    check_token(L, P, TOK_CLOSE_PAREN, NULL, "expected align(#) on line %d", P->line);
                    break;

                default:
                    luaL_error(L, "expected align(#) on line %d", P->line);
                }

                /* __attribute__(aligned(#)) is only supposed to increase alignment */
                ct->align_mask = max(align, ct->align_mask);

            } else if (IS_LITERAL(*tok, "packed") || IS_LITERAL(*tok, "__packed__")) {
                ct->align_mask = 0;
                ct->is_packed = 1;

            } else if (IS_LITERAL(*tok, "mode") || IS_LITERAL(*tok, "__mode__")) {

                check_token(L, P, TOK_OPEN_PAREN, NULL, "expected mode(MODE) on line %d", P->line);

                require_token(L, P, tok);
                if (tok->type != TOK_TOKEN) {
                    luaL_error(L, "expected mode(MODE) on line %d", P->line);
                }

                if (ct->type == FLOAT_TYPE || ct->type == DOUBLE_TYPE) {
                    struct {char ch; float v;} af;
                    struct {char ch; double v;} ad;

                    if (IS_LITERAL(*tok, "SF") || IS_LITERAL(*tok, "__SF__")) {
                        ct->type = FLOAT_TYPE;
                        ct->base_size = sizeof(float);
                        ct->align_mask = ALIGNOF(af);

                    } else if (IS_LITERAL(*tok, "DF") || IS_LITERAL(*tok, "__DF__")) {
                        ct->type = DOUBLE_TYPE;
                        ct->base_size = sizeof(double);
                        ct->align_mask = ALIGNOF(ad);

                    } else {
                        luaL_error(L, "unexpected mode on line %d", P->line);
                    }

                } else {
                    struct {char ch; uint16_t v;} a16;
                    struct {char ch; uint32_t v;} a32;
                    struct {char ch; uint64_t v;} a64;

                    if (IS_LITERAL(*tok, "QI") || IS_LITERAL(*tok, "__QI__")
                            || IS_LITERAL(*tok, "byte") || IS_LITERAL(*tok, "__byte__")
                            ) {
                        ct->type = INT8_TYPE;
                        ct->base_size = sizeof(uint8_t);
                        ct->align_mask = 0;

                    } else if (IS_LITERAL(*tok, "HI") || IS_LITERAL(*tok, "__HI__")) {
                        ct->type = INT16_TYPE;
                        ct->base_size = sizeof(uint16_t);
                        ct->align_mask = ALIGNOF(a16);

                    } else if (IS_LITERAL(*tok, "SI") || IS_LITERAL(*tok, "__SI__")
#if defined ARCH_X86 || defined ARCH_ARM
                            || IS_LITERAL(*tok, "word") || IS_LITERAL(*tok, "__word__")
                            || IS_LITERAL(*tok, "pointer") || IS_LITERAL(*tok, "__pointer__")
#endif
                            ) {
                        ct->type = INT32_TYPE;
                        ct->base_size = sizeof(uint32_t);
                        ct->align_mask = ALIGNOF(a32);

                    } else if (IS_LITERAL(*tok, "DI") || IS_LITERAL(*tok, "__DI__")
#if defined ARCH_X64 || defined ARCH_PPC64
                            || IS_LITERAL(*tok, "word") || IS_LITERAL(*tok, "__word__")
                            || IS_LITERAL(*tok, "pointer") || IS_LITERAL(*tok, "__pointer__")
#endif
                            ) {
                        ct->type = INT64_TYPE;
                        ct->base_size = sizeof(uint64_t);
                        ct->align_mask = ALIGNOF(a64);

                    } else {
                        luaL_error(L, "unexpected mode on line %d", P->line);
                    }
                }

                check_token(L, P, TOK_CLOSE_PAREN, NULL, "expected mode(MODE) on line %d", P->line);

            } else if (IS_LITERAL(*tok, "cdecl") || IS_LITERAL(*tok, "__cdecl__")) {
                ct->calling_convention = C_CALL;

            } else if (IS_LITERAL(*tok, "fastcall") || IS_LITERAL(*tok, "__fastcall__")) {
                ct->calling_convention = FAST_CALL;

            } else if (IS_LITERAL(*tok, "stdcall") || IS_LITERAL(*tok, "__stdcall__")) {
                ct->calling_convention = STD_CALL;
            }
            /* ignore unknown tokens within parentheses */
        }
        return 1;

    } else if (IS_LITERAL(*tok, "__cdecl")) {
        ct->calling_convention = C_CALL;
        return 1;

    } else if (IS_LITERAL(*tok, "__fastcall")) {
        ct->calling_convention = FAST_CALL;
        return 1;

    } else if (IS_LITERAL(*tok, "__stdcall")) {
        ct->calling_convention = STD_CALL;
        return 1;

    } else if (IS_LITERAL(*tok, "__extension__") || IS_LITERAL(*tok, "extern")) {
        /* ignore */
        return 1;

    } else {
        return 0;
    }
}

/* parses out the base type of a type expression in a function declaration,
 * struct definition, typedef etc
 *
 * leaves the usr value of the type on the stack
 */
int parse_type(lua_State* L, struct parser* P, struct ctype* ct)
{
    struct token tok;
    int top = lua_gettop(L);

    memset(ct, 0, sizeof(*ct));

    require_token(L, P, &tok);

    /* get const/volatile before the base type */
    for (;;) {
        if (tok.type != TOK_TOKEN) {
            return luaL_error(L, "unexpected value before type name on line %d", P->line);

        } else if (IS_CONST(tok)) {
            ct->const_mask = 1;
            require_token(L, P, &tok);

        } else if (IS_VOLATILE(tok) ||
                   IS_RESTRICT(tok) ||
                   IS_LITERAL(tok, "static") ||
                   IS_INLINE(tok)) {
            /* ignored for now */
            require_token(L, P, &tok);
        } else if (parse_attribute(L, P, &tok, ct, NULL)) {
            /* get function attributes before the return type */
            require_token(L, P, &tok);

        } else {
            break;
        }
    }

    /* get base type */
    if (tok.type != TOK_TOKEN) {
        return luaL_error(L, "unexpected value before type name on line %d", P->line);

    } else if (IS_LITERAL(tok, "struct")) {
        ct->type = STRUCT_TYPE;
        parse_record(L, P, ct);

    } else if (IS_LITERAL(tok, "union")) {
        ct->type = UNION_TYPE;
        parse_record(L, P, ct);

    } else if (IS_LITERAL(tok, "enum")) {
        ct->type = ENUM_TYPE;
        parse_record(L, P, ct);

    } else {
        put_back(P);

        /* lookup type */
        push_upval(L, &types_key);
        parse_type_name(L, P);
        lua_rawget(L, -2);
        lua_remove(L, -2);

        if (lua_isnil(L, -1)) {
            lua_pushlstring(L, tok.str, tok.size);
            return luaL_error(L, "unknown type %s on line %d", lua_tostring(L, -1), P->line);
        }

        instantiate_typedef(P, ct, (const struct ctype*) lua_touserdata(L, -1));

        /* we only want the usr tbl from the ctype in the types tbl */
        lua_getuservalue(L, -1);
        lua_replace(L, -2);
    }

    while (next_token(L, P, &tok)) {
        if (tok.type != TOK_TOKEN) {
            put_back(P);
            break;

        } else if (IS_CONST(tok) || IS_VOLATILE(tok)) {
            /* ignore for now */

        } else {
            put_back(P);
            break;
        }
    }

    assert(lua_gettop(L) == top + 1 && (lua_istable(L, -1) || lua_isnil(L, -1)));
    return 0;
}

enum name_type {
    BOTH,
    FRONT,
    BACK,
};

static void append_type_name(luaL_Buffer* B, int usr, const struct ctype* ct, enum name_type type)
{
    size_t i;
    lua_State* L = B->L;

    usr = lua_absindex(L, usr);

    if (type == FRONT || type == BOTH) {
        if (ct->type != FUNCTION_PTR_TYPE && (ct->const_mask & (1 << ct->pointers))) {
            luaL_addstring(B, "const ");
        }

        if (ct->is_unsigned) {
            luaL_addstring(B, "unsigned ");
        }

        switch (ct->type) {
        case ENUM_TYPE:
            luaL_addstring(B, "enum ");
            goto get_name;

        case STRUCT_TYPE:
            luaL_addstring(B, "struct ");
            goto get_name;

        case UNION_TYPE:
            luaL_addstring(B, "union ");
            goto get_name;

        get_name:
            lua_pushlightuserdata(L, &g_name_key);
            lua_rawget(L, usr);
            luaL_addvalue(B);
            break;

        case FUNCTION_TYPE:
        case FUNCTION_PTR_TYPE:
            lua_pushlightuserdata(L, &g_front_name_key);
            lua_rawget(L, usr);
            luaL_addvalue(B);
            break;

        case VOID_TYPE:
            luaL_addstring(B, "void");
            break;
        case BOOL_TYPE:
            luaL_addstring(B, "bool");
            break;
        case DOUBLE_TYPE:
            luaL_addstring(B, "double");
            break;
        case LONG_DOUBLE_TYPE:
            luaL_addstring(B, "long double");
            break;
        case FLOAT_TYPE:
            luaL_addstring(B, "float");
            break;
        case COMPLEX_LONG_DOUBLE_TYPE:
            luaL_addstring(B, "long complex double");
            break;
        case COMPLEX_DOUBLE_TYPE:
            luaL_addstring(B, "complex double");
            break;
        case COMPLEX_FLOAT_TYPE:
            luaL_addstring(B, "complex float");
            break;
        case INT8_TYPE:
            luaL_addstring(B, "char");
            break;
        case INT16_TYPE:
            luaL_addstring(B, "short");
            break;
        case INT32_TYPE:
            luaL_addstring(B, "int");
            break;
        case INT64_TYPE:
            luaL_addstring(B, "long long");
            break;

        case INTPTR_TYPE:
            if (sizeof(intptr_t) == sizeof(int32_t)) {
                luaL_addstring(B, "long");
            } else if (sizeof(intptr_t) == sizeof(int64_t)) {
                luaL_addstring(B, "long long");
            } else {
                luaL_error(L, "internal error - bad type");
            }
            break;

        default:
            luaL_error(L, "internal error - bad type %d", ct->type);
        }

        for (i = 0; i < ct->pointers - ct->is_array; i++) {
            luaL_addchar(B, '*');
            if (ct->const_mask & (1 << (ct->pointers - i - 1))) {
                luaL_addstring(B, " const");
            }
        }
    }

    if (type == BOTH || type == BACK) {
        if (ct->is_reference) {
            luaL_addstring(B, " &");
        }

        if (ct->is_variable_array && !ct->variable_size_known) {
            luaL_addstring(B, "[?]");
        } else if (ct->is_array) {
            lua_pushfstring(L, "[%d]", (int) ct->array_size);
            luaL_addvalue(B);
        }

        if (ct->type == FUNCTION_PTR_TYPE || ct->type == FUNCTION_TYPE) {
            lua_pushlightuserdata(L, &g_back_name_key);
            lua_rawget(L, usr);
            luaL_addvalue(B);
        }

        if (ct->is_bitfield) {
            lua_pushfstring(L, " : %d", (int) ct->bit_size);
            luaL_addvalue(B);
        }
    }
}

void push_type_name(lua_State* L, int usr, const struct ctype* ct)
{
    luaL_Buffer B;
    usr = lua_absindex(L, usr);
    luaL_buffinit(L, &B);
    append_type_name(&B, usr, ct, BOTH);
    luaL_pushresult(&B);
}

static void push_function_type_strings(lua_State* L, int usr, const struct ctype* ct)
{
    size_t i, args;
    luaL_Buffer B;
    int top = lua_gettop(L);
    const struct ctype* ret_ct;

    int arg_ct = top+3;
    int arg_usr = top+4;
    int ret_usr = top+6;

    usr = lua_absindex(L, usr);

    /* return type */
    lua_settop(L, top+4); /* room for two returns and two temp positions */
    lua_rawgeti(L, usr, 0);
    lua_getuservalue(L, -1);
    ret_ct = (const struct ctype*) lua_touserdata(L, -2);

    luaL_buffinit(L, &B);
    append_type_name(&B, ret_usr, ret_ct, FRONT);

    if (ret_ct->type != FUNCTION_TYPE && ret_ct->type != FUNCTION_PTR_TYPE) {
        luaL_addchar(&B, ' ');
    }

    switch (ct->calling_convention) {
    case STD_CALL:
        luaL_addstring(&B, "(__stdcall *");
        break;
    case FAST_CALL:
        luaL_addstring(&B, "(__fastcall *");
        break;
    case C_CALL:
        luaL_addstring(&B, "(*");
        break;
    default:
        luaL_error(L, "internal error - unknown calling convention");
    }

    luaL_pushresult(&B);
    lua_replace(L, top+1);

    luaL_buffinit(L, &B);
    luaL_addstring(&B, ")(");

    /* arguments */
    args = lua_rawlen(L, usr);
    for (i = 1; i <= args; i++) {
        if (i > 1) {
            luaL_addstring(&B, ", ");
        }

        /* note push the arg and user value below the indexes used by the buffer
         * and use indexes relative to top to avoid problems due to the buffer
         * system pushing a variable number of arguments onto the stack */
        lua_rawgeti(L, usr, (int) i);
        lua_replace(L, arg_ct);
        lua_getuservalue(L, arg_ct);
        lua_replace(L, arg_usr);
        append_type_name(&B, arg_usr, (const struct ctype*) lua_touserdata(L, arg_ct), BOTH);
    }

    luaL_addstring(&B, ")");
    append_type_name(&B, ret_usr, ret_ct, BACK);
    luaL_pushresult(&B);
    lua_replace(L, top+2);

    lua_settop(L, top+2);
    assert(lua_isstring(L, top+1) && lua_isstring(L, top+2));
}

/* parses from after the opening paranthesis to after the closing parenthesis */
static void parse_function_arguments(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct)
{
    struct token tok;
    int args = 0;
    int top = lua_gettop(L);

    ct_usr = lua_absindex(L, ct_usr);

    for (;;) {
        require_token(L, P, &tok);

        if (tok.type == TOK_CLOSE_PAREN) {
            break;
        }

        if (args) {
            if (tok.type != TOK_COMMA) {
                luaL_error(L, "unexpected token in function argument %d on line %d", args, P->line);
            }

            require_token(L, P, &tok);
        }

        if (tok.type == TOK_VA_ARG) {
            ct->has_var_arg = true;
            check_token(L, P, TOK_CLOSE_PAREN, "", "unexpected token after ... in function on line %d", P->line);
            break;

        } else if (tok.type == TOK_TOKEN) {
            struct ctype at;

            put_back(P);
            parse_type(L, P, &at);
            parse_argument(L, P, -1, &at, NULL, NULL);

            assert(lua_gettop(L) == top + 2);

            /* array arguments are just treated as their base pointer type */
            at.is_array = 0;

            /* check for the c style int func(void) and error on other uses of arguments of type void */
            if (at.type == VOID_TYPE && at.pointers == 0) {
                if (args) {
                    luaL_error(L, "can't have argument of type void on line %d", P->line);
                }

                check_token(L, P, TOK_CLOSE_PAREN, "", "unexpected void in function on line %d", P->line);
                lua_pop(L, 2);
                break;
            }

            push_ctype(L, -1, &at);
            lua_rawseti(L, ct_usr, ++args);

            lua_pop(L, 2); /* parse_type and parse_argument at_usr */

        } else {
            luaL_error(L, "unexpected token in function argument %d on line %d", args+1, P->line);
        }
    }

    assert(lua_gettop(L) == top);
}

static int max_bitfield_size(int type)
{
    switch (type) {
    case BOOL_TYPE:
        return 1;
    case INT8_TYPE:
        return 8;
    case INT16_TYPE:
        return 16;
    case INT32_TYPE:
    case ENUM_TYPE:
        return 32;
    case INT64_TYPE:
        return 64;
    default:
        return -1;
    }
}

static struct ctype* parse_argument2(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct, struct token* name, struct parser* asmname);

/* parses from after the first ( in a function declaration or function pointer
 * can be one of:
 * void foo(...) before ...
 * void (foo)(...) before foo
 * void (* <>)(...) before <> which is the inner type
 */
static struct ctype* parse_function(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct, struct token* name, struct parser* asmname)
{
    /* We have a function pointer or a function. The usr table will
     * get replaced by the canonical one (if there is one) in
     * find_canonical_usr after all the arguments and returns have
     * been parsed. */
    struct token tok;
    int top = lua_gettop(L);
    struct ctype* ret;

    lua_newtable(L);
    ret = push_ctype(L, ct_usr, ct);
    lua_rawseti(L, -2, 0);
    ct_usr = lua_gettop(L);

    memset(ct, 0, sizeof(*ct));
    ct->base_size = sizeof(void (*)());
    ct->align_mask = min(FUNCTION_ALIGN_MASK, P->align_mask);
    ct->type = FUNCTION_TYPE;
    ct->is_defined = 1;

    if (name->type == TOK_NIL) {
        for (;;) {
            require_token(L, P, &tok);

            if (tok.type == TOK_STAR) {

                if (ct->type == FUNCTION_TYPE) {
                    ct->type = FUNCTION_PTR_TYPE;
                } else if (ct->pointers == POINTER_MAX) {
                    luaL_error(L, "maximum number of pointer derefs reached - use a struct to break up the pointers on line %d", P->line);
                } else {
                    ct->pointers++;
                    ct->const_mask <<= 1;
                }

            } else if (parse_attribute(L, P, &tok, ct, asmname)) {
                /* parse_attribute sets the appropriate fields */

            } else {
                /* call parse_argument to handle the inner contents
                 * e.g. the <> in "void (* <>) (...)". Note that the
                 * inner contents can itself be a function, a function
                 * ptr, array, etc (e.g. "void (*signal(int sig, void
                 * (*func)(int)))(int)" ).
                 */
                put_back(P);
                ct = parse_argument2(L, P, ct_usr, ct, name, asmname);
                break;
            }
        }

        check_token(L, P, TOK_CLOSE_PAREN, NULL, "unexpected token in function on line %d", P->line);
        check_token(L, P, TOK_OPEN_PAREN, NULL, "unexpected token in function on line %d", P->line);
    }

    parse_function_arguments(L, P, ct_usr, ct);

    /* if we have an inner function then set the outer function ptr as its
     * return type and return the inner function
     * e.g. for void (* <signal(int, void (*)(int))> )(int) inner is
     * surrounded by <>, return type is void (*)(int)
     */
    if (lua_gettop(L) == ct_usr+1) {
        lua_replace(L, ct_usr);
    }

    assert(lua_gettop(L) == top + 1 && lua_istable(L, -1));
    return ret;
}

static struct ctype* parse_argument2(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct, struct token* name, struct parser* asmname)
{
    struct token tok;
    int top = lua_gettop(L);
    int ft_usr = 0;

    luaL_checkstack(L, 10, "function too complex");
    ct_usr = lua_absindex(L, ct_usr);

    for (;;) {
        if (!next_token(L, P, &tok)) {
            /* we've reached the end of the string */
            break;

        } else if (tok.type == TOK_STAR) {
            if (ct->pointers == POINTER_MAX) {
                luaL_error(L, "maximum number of pointer derefs reached - use a struct to break up the pointers on line %d", P->line);
            }

            ct->pointers++;
            ct->const_mask <<= 1;

            /* __declspec(align(#)) may come before the type in a member */
            if (!ct->is_packed) {
                ct->align_mask = max(min(PTR_ALIGN_MASK, P->align_mask), ct->align_mask);
            }

        } else if (tok.type == TOK_REFERENCE) {
            ct->is_reference = 1;

        } else if (parse_attribute(L, P, &tok, ct, asmname)) {
            /* parse attribute has filled out appropriate fields in type */

        } else if (tok.type == TOK_OPEN_PAREN) {
            ct = parse_function(L, P, ct_usr, ct, name, asmname);
            ft_usr = lua_gettop(L);

        } else if (tok.type == TOK_OPEN_SQUARE) {
            /* array */
            if (ct->pointers == POINTER_MAX) {
                luaL_error(L, "maximum number of pointer derefs reached - use a struct to break up the pointers");
            }
            ct->is_array = 1;
            ct->pointers++;
            ct->const_mask <<= 1;
            require_token(L, P, &tok);

            if (ct->pointers == 1 && !ct->is_defined) {
                luaL_error(L, "array of undefined type on line %d", P->line);
            }

            if (ct->is_variable_struct || ct->is_variable_array) {
                luaL_error(L, "can't have an array of a variably sized type on line %d", P->line);
            }

            if (tok.type == TOK_QUESTION) {
                ct->is_variable_array = 1;
                ct->variable_increment = (ct->pointers > 1) ? sizeof(void*) : ct->base_size;
                check_token(L, P, TOK_CLOSE_SQUARE, "", "invalid character in array on line %d", P->line);

            } else if (tok.type == TOK_CLOSE_SQUARE) {
                ct->array_size = 0;

            } else if (tok.type == TOK_TOKEN && IS_RESTRICT(tok)) {
                /* odd gcc extension foo[__restrict] for arguments */
                ct->array_size = 0;
                check_token(L, P, TOK_CLOSE_SQUARE, "", "invalid character in array on line %d", P->line);

            } else {
                int64_t asize;
                put_back(P);
                asize = calculate_constant(L, P);
                if (asize < 0) {
                    luaL_error(L, "array size can not be negative on line %d", P->line);
                }
                ct->array_size = (size_t) asize;
                check_token(L, P, TOK_CLOSE_SQUARE, "", "invalid character in array on line %d", P->line);
            }

        } else if (tok.type == TOK_COLON) {
            int64_t bsize = calculate_constant(L, P);

            if (ct->pointers || bsize < 0 || bsize > max_bitfield_size(ct->type)) {
                luaL_error(L, "invalid bitfield on line %d", P->line);
            }

            ct->is_bitfield = 1;
            ct->bit_size = (unsigned) bsize;

        } else if (tok.type != TOK_TOKEN) {
            /* we've reached the end of the declaration */
            put_back(P);
            break;

        } else if (IS_CONST(tok)) {
            ct->const_mask |= 1;

        } else if (IS_VOLATILE(tok) || IS_RESTRICT(tok)) {
            /* ignored for now */

        } else {
            *name = tok;
        }
    }

    assert((ft_usr == 0 && lua_gettop(L) == top) || (lua_gettop(L) == top + 1 && ft_usr == top + 1 && (lua_istable(L, -1) || lua_isnil(L, -1))));
    return ct;
}

static void find_canonical_usr(lua_State* L, int ct_usr, const struct ctype *ct)
{
    struct ctype rt;
    int top = lua_gettop(L);
    int types;

    if (ct->type != FUNCTION_PTR_TYPE && ct->type != FUNCTION_TYPE) {
        return;
    }

    luaL_checkstack(L, 10, "function too complex");
    ct_usr = lua_absindex(L, ct_usr);

    /* check to see if we already have the canonical usr table */
    lua_pushlightuserdata(L, &g_name_key);
    lua_rawget(L, ct_usr);
    if (!lua_isnil(L, -1)) {
        lua_pop(L, 1);
        assert(top == lua_gettop(L));
        return;
    }
    lua_pop(L, 1);

    assert(top == lua_gettop(L));

    /* first canonize the return type */
    lua_rawgeti(L, ct_usr, 0);
    rt = *(struct ctype*) lua_touserdata(L, -1);
    lua_getuservalue(L, -1);
    find_canonical_usr(L, -1, &rt);
    push_ctype(L, -1, &rt);
    lua_rawseti(L, ct_usr, 0);
    lua_pop(L, 2); /* return ctype and usr */

    assert(top == lua_gettop(L));

    /* look up the type string in the types table */
    push_upval(L, &types_key);
    types = lua_gettop(L);

    push_function_type_strings(L, ct_usr, ct);
    lua_pushvalue(L, -2);
    lua_pushvalue(L, -2);
    lua_concat(L, 2);

    lua_pushvalue(L, -1);
    lua_rawget(L, types);

    assert(lua_gettop(L) == types + 4 && types == top + 1);
    /* stack: types, front, back, both, looked up value */

    if (lua_isnil(L, -1)) {
        lua_pop(L, 1);

        lua_pushlightuserdata(L, &g_front_name_key);
        lua_pushvalue(L, -4);
        lua_rawset(L, ct_usr);

        lua_pushlightuserdata(L, &g_back_name_key);
        lua_pushvalue(L, -3);
        lua_rawset(L, ct_usr);

        lua_pushlightuserdata(L, &g_name_key);
        lua_pushvalue(L, -2);
        lua_rawset(L, ct_usr);

        lua_pushvalue(L, -1);
        push_ctype(L, ct_usr, ct);
        lua_rawset(L, types);
    } else {
        lua_getuservalue(L, -1);
        lua_replace(L, ct_usr);
        lua_pop(L, 1);
    }

    lua_pop(L, 4);
    assert(top == lua_gettop(L) && types == top + 1);
}


/* parses after the main base type of a typedef, function argument or
 * struct/union member
 * eg for const void* bar[3] the base type is void with the subtype so far of
 * const, this parses the "* bar[3]" and updates the type argument
 *
 * ct_usr and type must be as filled out by parse_type
 *
 * pushes the updated user value on the top of the stack
 */
void parse_argument(lua_State* L, struct parser* P, int ct_usr, struct ctype* ct, struct token* pname, struct parser* asmname)
{
    struct token tok, name;
    int top = lua_gettop(L);

    memset(&name, 0, sizeof(name));
    parse_argument2(L, P, ct_usr, ct, &name, asmname);

    for (;;) {
        if (!next_token(L, P, &tok)) {
            break;
        } else if (parse_attribute(L, P, &tok, ct, asmname)) {
            /* parse_attribute sets the appropriate fields */
        } else {
            put_back(P);
            break;
        }
    }

    if (lua_gettop(L) == top) {
        lua_pushvalue(L, ct_usr);
    }

    find_canonical_usr(L, -1, ct);

    if (pname) {
        *pname = name;
    }
}

static void parse_typedef(lua_State* L, struct parser* P)
{
    struct token tok;
    struct ctype base_type;
    int top = lua_gettop(L);

    parse_type(L, P, &base_type);

    for (;;) {
        struct ctype arg_type = base_type;
        struct token name;

        memset(&name, 0, sizeof(name));

        assert(lua_gettop(L) == top + 1);
        parse_argument(L, P, -1, &arg_type, &name, NULL);
        assert(lua_gettop(L) == top + 2);

        if (!name.size) {
            luaL_error(L, "Can't have a typedef without a name on line %d", P->line);
        } else if (arg_type.is_variable_array) {
            luaL_error(L, "Can't typedef a variable length array on line %d", P->line);
        }

        push_upval(L, &types_key);
        lua_pushlstring(L, name.str, name.size);
        push_ctype(L, -3, &arg_type);
        lua_rawset(L, -3);
        lua_pop(L, 2); /* types and parse_argument usr tbl */

        require_token(L, P, &tok);

        if (tok.type == TOK_SEMICOLON) {
            break;
        } else if (tok.type != TOK_COMMA) {
            luaL_error(L, "Unexpected character in typedef on line %d", P->line);
        }
    }

    lua_pop(L, 1); /* parse_type usr tbl */
    assert(lua_gettop(L) == top);
}

static bool is_hex(char ch)
{ return ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'); }

static bool is_digit(char ch)
{ return '0' <= ch && ch <= '9'; }

static int from_hex(char ch)
{
    if (ch >= 'a') {
        return ch - 'a' + 10;
    } else if (ch >= 'A') {
        return ch - 'A' + 10;
    } else {
        return ch - '0';
    }
}

static void push_strings(lua_State* L, struct parser* P)
{
    luaL_Buffer B;
    luaL_buffinit(L, &B);

    for (;;) {
        const char *p, *e;
        char *t, *s;
        struct token tok;

        require_token(L, P, &tok);
        if (tok.type != TOK_STRING) {
            break;
        }

        p = tok.str;
        e = p + tok.size;

        t = luaL_prepbuffsize(&B, tok.size);
        s = t;

        while (p < e) {
            if (*p == '\\') {
                if (++p == e) {
                    luaL_error(L, "parse error in string");
                }
                switch (*p) {
                case '\\': *(t++) = '\\'; p++; break;
                case '\"': *(t++) = '\"'; p++; break;
                case '\'': *(t++) = '\''; p++; break;
                case 'n': *(t++) = '\n'; p++; break;
                case 'r': *(t++) = '\r'; p++; break;
                case 'b': *(t++) = '\b'; p++; break;
                case 't': *(t++) = '\t'; p++; break;
                case 'f': *(t++) = '\f'; p++; break;
                case 'a': *(t++) = '\a'; p++; break;
                case 'v': *(t++) = '\v'; p++; break;
                case 'e': *(t++) = 0x1B; p++; break;
                case 'x':
                    {
                        uint8_t u;
                        p++;
                        if (p + 2 > e || !is_hex(p[0]) || !is_hex(p[1])) {
                            luaL_error(L, "parse error in string");
                        }
                        u = (from_hex(p[0]) << 4) | from_hex(p[1]);
                        *(t++) = *(char*) &u;
                        p += 2;
                        break;
                    }
                default:
                    {
                        uint8_t u;
                        const char* e2 = min(p + 3, e);
                        if (!is_digit(*p)) {
                            luaL_error(L, "parse error in string");
                        }
                        u = *p - '0';
                        p++;
                        while (is_digit(*p) && p < e2) {
                            u = 10*u + *p-'0';
                            p++;
                        }
                        *(t++) = *(char*) &u;
                        break;
                    }
                }
            } else {
                *(t++) = *(p++);
            }
        }

        luaL_addsize(&B, t-s);
    }

    luaL_pushresult(&B);
}

static void parse_constant_assignemnt(lua_State* L,
                                      struct parser* P,
                                      const struct ctype* type,
                                      const struct token* name)
{
    int64_t val = calculate_constant(L, P);

    check_token(L, P, TOK_SEMICOLON, "", "expected ; after constant definition on line %d", P->line);

    push_upval(L, &constants_key);
    lua_pushlstring(L, name->str, name->size);

    switch (type->type) {
        case INT8_TYPE:
        case INT16_TYPE:
        case INT32_TYPE:
            if (type->is_unsigned)
                lua_pushinteger(L, (unsigned int) val);
            else
                lua_pushinteger(L, (int) val);
            break;

        default:
            luaL_error(L, "expected a valid 8-, 16-, or 32-bit signed or unsigned integer type after 'static const' on line %d", P->line);
    }

    lua_rawset(L, -3);
    lua_pop(L, 2); /*constants and type*/
}

#define END 0
#define PRAGMA_POP 1

static int parse_root(lua_State* L, struct parser* P)
{
    int top = lua_gettop(L);
    struct token tok;

    while (next_token(L, P, &tok)) {
        /* we can have:
         * struct definition
         * enum definition
         * union definition
         * struct/enum/union declaration
         * typedef
         * function declaration
         * pragma pack
         */

        assert(lua_gettop(L) == top);

        if (tok.type == TOK_SEMICOLON) {
            /* empty semicolon in root continue on */

        } else if (tok.type == TOK_POUND) {

            check_token(L, P, TOK_TOKEN, "pragma", "unexpected pre processor directive on line %d", P->line);
            check_token(L, P, TOK_TOKEN, "pack", "unexpected pre processor directive on line %d", P->line);
            check_token(L, P, TOK_OPEN_PAREN, "", "invalid pack directive on line %d", P->line);

            require_token(L, P, &tok);

            if (tok.type == TOK_NUMBER) {
                if (tok.integer != 1 && tok.integer != 2 && tok.integer != 4 && tok.integer != 8 && tok.integer != 16) {
                    luaL_error(L, "pack directive with invalid pack size on line %d", P->line);
                }

                P->align_mask = (unsigned) (tok.integer - 1);
                check_token(L, P, TOK_CLOSE_PAREN, "", "invalid pack directive on line %d", P->line);

            } else if (tok.type == TOK_TOKEN && IS_LITERAL(tok, "push")) {
                int line = P->line;
                unsigned previous_alignment = P->align_mask;

                check_token(L, P, TOK_CLOSE_PAREN, "", "invalid pack directive on line %d", P->line);

                if (parse_root(L, P) != PRAGMA_POP) {
                    luaL_error(L, "reached end of string without a pragma pop to match the push on line %d", line);
                }

                P->align_mask = previous_alignment;

            } else if (tok.type == TOK_TOKEN && IS_LITERAL(tok, "pop")) {
                check_token(L, P, TOK_CLOSE_PAREN, "", "invalid pack directive on line %d", P->line);
                return PRAGMA_POP;

            } else {
                luaL_error(L, "invalid pack directive on line %d", P->line);
            }


        } else if (tok.type != TOK_TOKEN) {
            return luaL_error(L, "unexpected character on line %d", P->line);

        } else if (IS_LITERAL(tok, "__extension__")) {
            /* ignore */
            continue;

        } else if (IS_LITERAL(tok, "extern")) {
            /* ignore extern as data and functions can only be extern */
            continue;

        } else if (IS_LITERAL(tok, "typedef")) {
            parse_typedef(L, P);

        } else {
            /* type declaration, type definition, or function declaration */
            struct ctype type;
            struct token name;
            struct parser asmname;

            memset(&name, 0, sizeof(name));
            memset(&asmname, 0, sizeof(asmname));

            put_back(P);
            parse_type(L, P, &type);

            for (;;) {
                parse_argument(L, P, -1, &type, &name, &asmname);

                if (name.size) {
                    /* global/function declaration */

                    /* set asmname_tbl[name] = asmname */
                    if (asmname.next) {
                        push_upval(L, &asmname_key);
                        lua_pushlstring(L, name.str, name.size);
                        push_strings(L, &asmname);
                        lua_rawset(L, -3);
                        lua_pop(L, 1); /* asmname upval */
                    }

                    push_upval(L, &functions_key);
                    lua_pushlstring(L, name.str, name.size);
                    push_ctype(L, -3, &type);
                    lua_rawset(L, -3);
                    lua_pop(L, 1); /* functions upval */
                } else {
                    /* type declaration/definition - already been processed */
                }

                lua_pop(L, 1);

                if (!next_token(L, P, &tok)) {
                    break;
                }

                if (tok.type == TOK_COMMA) {
                    continue;
                }

                if (tok.type == TOK_OPEN_CURLY) {
                    int line = P->line;
                    int remaining = 1;
                    while (remaining > 0 && next_token(L, P, &tok)) {
                        if (tok.type == TOK_CLOSE_CURLY) {
                            remaining--;
                        } else if (tok.type == TOK_OPEN_CURLY) {
                            remaining++;
                        }
                    }
                    if (remaining > 0) {
                        luaL_error(L, "missing closing bracket for line %d", line);
                    }
                } else if (tok.type == TOK_ASSIGN) {
                    parse_constant_assignemnt(L, P, &type, &name);
                } else if (tok.type != TOK_SEMICOLON) {
                    luaL_error(L, "missing semicolon on line %d", P->line);
                }
                break;
            }

            lua_pop(L, 1);
        }
    }

    return END;
}

int ffi_cdef(lua_State* L)
{
    struct parser P;

    P.line = 1;
    P.prev = P.next = luaL_checkstring(L, 1);
    P.align_mask = DEFAULT_ALIGN_MASK;

    if (parse_root(L, &P) == PRAGMA_POP) {
        luaL_error(L, "pragma pop without an associated push on line %d", P.line);
    }

    return 0;
}

/* calculate_constant handles operator precedence by having a number of
 * recursive commands each of which computes the result at that level of
 * precedence and above. calculate_constant1 is the highest precedence
 */

static int64_t string_to_int(const char* str, size_t size)
{
    const char* end = str + size;
    char c = *str++;
    if (str < end)
    {
        if (c == '\\') {
            c = *str++;
            switch (c) {
            case '\'': c = '\''; break;
            case '\"': c = '\"'; break;
            case '\?': c = '\?'; break;
            case '\\': c = '\\'; break;
            case 'a': c = '\a'; break;
            case 'b': c = '\b'; break;
            case 'f': c = '\f'; break;
            case 'n': c = '\n'; break;
            case 'r': c = '\r'; break;
            case 't': c = '\t'; break;
            case 'v': c = '\v'; break;
            case 'e': c = 27; break;
            case 'x':
                c = 0;
                while (str < end) {
                    char d = *str++;
                    c *= 16;
                    if (d >= '0' && d <= '9') c += (d - '0');
                    else c += (d - 'a' + 10);
                }
                break;
            default:
                c = c - '0';
                while (str < end) {
                    char d = *str++;
                    c = c*8 + (d - '0');
                }
                break;
            }
        }
    }
    return c;
}

static int try_cast(lua_State* L)
{
    struct parser* P = (struct parser*) lua_touserdata(L, 1);
    struct ctype ct;
    struct token name, tok;
    memset(&name, 0, sizeof(name));

    parse_type(L, P, &ct);
    parse_argument(L, P, -1, &ct, &name, NULL);

    require_token(L, P, &tok);
    if (tok.type != TOK_CLOSE_PAREN || name.size) {
        return luaL_error(L, "invalid cast");
    }

    if (ct.pointers/* || ct.type != INT32_TYPE*/) {
        return luaL_error(L, "unsupported cast on line %d", P->line);
    }

    return 0;
}

static int64_t calculate_constant2(lua_State* L, struct parser* P, struct token* tok);

/* () */
static int64_t calculate_constant1(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t ret;

    if (tok->type == TOK_NUMBER) {
        ret = tok->integer;
        next_token(L, P, tok);
        return ret;

    } else if (tok->type == TOK_TOKEN) {
        /* look up name in constants table */
        push_upval(L, &constants_key);
        lua_pushlstring(L, tok->str, tok->size);
        lua_rawget(L, -2);
        lua_remove(L, -2); /* constants table */

        if (!lua_isnumber(L, -1)) {
            lua_pushlstring(L, tok->str, tok->size);
            luaL_error(L, "use of undefined constant %s on line %d", lua_tostring(L, -1), P->line);
        }

        ret = (int64_t) lua_tonumber(L, -1);
        lua_pop(L, 1);
        next_token(L, P, tok);
        return ret;

    } else if (tok->type == TOK_OPEN_PAREN) {
        struct parser before_cast = *P;
        int top = lua_gettop(L);

        /* see if this is a numeric cast, which we ignore */
        lua_pushcfunction(L, &try_cast);
        lua_pushlightuserdata(L, P);
        if (!lua_pcall(L, 1, 0, 0)) {
            next_token(L, P, tok);
            return calculate_constant2(L, P, tok);
        }
        lua_settop(L, top);

        *P = before_cast;
        ret = calculate_constant(L, P);

        require_token(L, P, tok);
        if (tok->type != TOK_CLOSE_PAREN) {
            luaL_error(L, "error whilst parsing constant at line %d", P->line);
        }

        next_token(L, P, tok);
        return ret;

    } else if (tok->type == TOK_STRING) {
        ret = string_to_int(tok->str, tok->size);

        next_token(L, P, tok);
        return ret;

    } else {
        return luaL_error(L, "unexpected token whilst parsing constant at line %d", P->line);
    }
}

/* ! and ~, unary + and -, and sizeof */
static int64_t calculate_constant2(lua_State* L, struct parser* P, struct token* tok)
{
    if (tok->type == TOK_LOGICAL_NOT) {
        require_token(L, P, tok);
        return !calculate_constant2(L, P, tok);

    } else if (tok->type == TOK_BITWISE_NOT) {
        require_token(L, P, tok);
        return ~calculate_constant2(L, P, tok);

    } else if (tok->type == TOK_PLUS) {
        require_token(L, P, tok);
        return calculate_constant2(L, P, tok);

    } else if (tok->type == TOK_MINUS) {
        require_token(L, P, tok);
        return -calculate_constant2(L, P, tok);

    } else if (tok->type == TOK_TOKEN &&
            (IS_LITERAL(*tok, "sizeof")
             || IS_LITERAL(*tok, "alignof")
             || IS_LITERAL(*tok, "__alignof__")
             || IS_LITERAL(*tok, "__alignof"))) {

        bool issize = IS_LITERAL(*tok, "sizeof");
        struct ctype type;

        require_token(L, P, tok);
        if (tok->type != TOK_OPEN_PAREN) {
            luaL_error(L, "invalid sizeof at line %d", P->line);
        }

        parse_type(L, P, &type);
        parse_argument(L, P, -1, &type, NULL, NULL);
        lua_pop(L, 2);

        require_token(L, P, tok);
        if (tok->type != TOK_CLOSE_PAREN) {
            luaL_error(L, "invalid sizeof at line %d", P->line);
        }

        next_token(L, P, tok);

        return issize ? ctype_size(L, &type) : type.align_mask + 1;

    } else {
        return calculate_constant1(L, P, tok);
    }
}

/* binary * / and % (left associative) */
static int64_t calculate_constant3(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant2(L, P, tok);

    for (;;) {
        if (tok->type == TOK_MULTIPLY) {
            require_token(L, P, tok);
            left *= calculate_constant2(L, P, tok);

        } else if (tok->type == TOK_DIVIDE) {
            require_token(L, P, tok);
            left /= calculate_constant2(L, P, tok);

        } else if (tok->type == TOK_MODULUS) {
            require_token(L, P, tok);
            left %= calculate_constant2(L, P, tok);

        } else {
            return left;
        }
    }
}

/* binary + and - (left associative) */
static int64_t calculate_constant4(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant3(L, P, tok);

    for (;;) {
        if (tok->type == TOK_PLUS) {
            require_token(L, P, tok);
            left += calculate_constant3(L, P, tok);

        } else if (tok->type == TOK_MINUS) {
            require_token(L, P, tok);
            left -= calculate_constant3(L, P, tok);

        } else {
            return left;
        }
    }
}

/* binary << and >> (left associative) */
static int64_t calculate_constant5(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant4(L, P, tok);

    for (;;) {
        if (tok->type == TOK_LEFT_SHIFT) {
            require_token(L, P, tok);
            left <<= calculate_constant4(L, P, tok);

        } else if (tok->type == TOK_RIGHT_SHIFT) {
            require_token(L, P, tok);
            left >>= calculate_constant4(L, P, tok);

        } else {
            return left;
        }
    }
}

/* binary <, <=, >, and >= (left associative) */
static int64_t calculate_constant6(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant5(L, P, tok);

    for (;;) {
        if (tok->type == TOK_LESS) {
            require_token(L, P, tok);
            left = (left < calculate_constant5(L, P, tok));

        } else if (tok->type == TOK_LESS_EQUAL) {
            require_token(L, P, tok);
            left = (left <= calculate_constant5(L, P, tok));

        } else if (tok->type == TOK_GREATER) {
            require_token(L, P, tok);
            left = (left > calculate_constant5(L, P, tok));

        } else if (tok->type == TOK_GREATER_EQUAL) {
            require_token(L, P, tok);
            left = (left >= calculate_constant5(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary ==, != (left associative) */
static int64_t calculate_constant7(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant6(L, P, tok);

    for (;;) {
        if (tok->type == TOK_EQUAL) {
            require_token(L, P, tok);
            left = (left == calculate_constant6(L, P, tok));

        } else if (tok->type == TOK_NOT_EQUAL) {
            require_token(L, P, tok);
            left = (left != calculate_constant6(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary & (left associative) */
static int64_t calculate_constant8(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant7(L, P, tok);

    for (;;) {
        if (tok->type == TOK_BITWISE_AND) {
            require_token(L, P, tok);
            left = (left & calculate_constant7(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary ^ (left associative) */
static int64_t calculate_constant9(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant8(L, P, tok);

    for (;;) {
        if (tok->type == TOK_BITWISE_XOR) {
            require_token(L, P, tok);
            left = (left ^ calculate_constant8(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary | (left associative) */
static int64_t calculate_constant10(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant9(L, P, tok);

    for (;;) {
        if (tok->type == TOK_BITWISE_OR) {
            require_token(L, P, tok);
            left = (left | calculate_constant9(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary && (left associative) */
static int64_t calculate_constant11(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant10(L, P, tok);

    for (;;) {
        if (tok->type == TOK_LOGICAL_AND) {
            require_token(L, P, tok);
            left = (left && calculate_constant10(L, P, tok));

        } else {
            return left;
        }
    }
}

/* binary || (left associative) */
static int64_t calculate_constant12(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant11(L, P, tok);

    for (;;) {
        if (tok->type == TOK_LOGICAL_OR) {
            require_token(L, P, tok);
            left = (left || calculate_constant11(L, P, tok));

        } else {
            return left;
        }
    }
}

/* ternary ?: (right associative) */
static int64_t calculate_constant13(lua_State* L, struct parser* P, struct token* tok)
{
    int64_t left = calculate_constant12(L, P, tok);

    if (tok->type == TOK_QUESTION) {
        int64_t middle, right;
        require_token(L, P, tok);
        middle = calculate_constant13(L, P, tok);
        if (tok->type != TOK_COLON) {
            luaL_error(L, "invalid ternery (? :) in constant on line %d", P->line);
        }
        require_token(L, P, tok);
        right = calculate_constant13(L, P, tok);
        return left ? middle : right;

    } else {
        return left;
    }
}

int64_t calculate_constant(lua_State* L, struct parser* P)
{
    struct token tok;
    int64_t ret;
    require_token(L, P, &tok);
    ret = calculate_constant13(L, P, &tok);

    if (tok.type != TOK_NIL) {
        put_back(P);
    }

    return ret;
}