xcb 0.8.2

Rust bindings and wrappers for XCB
Documentation
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
#!/usr/bin/env python3
# Copyright (c) 2016 Remi Thebault <remi.thebault@gmail.com>
#
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without
# limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software
# is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions
# of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
# ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
# IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
'''
script that generates rust code from xcb xml definitions
Each invokation of this script generates one ffi file and one
rust file for an extension or the main X Protocol.

Usage: ./rs_client.py -o src xml/xproto.xml
'''

import sys
import os
import re



class SourceFile(object):
    '''
    buffer to append code in various sections of a file
    in any order
    '''

    _one_indent_level = '    '

    def __init__(self):
        self._section = 0
        self._lines = []
        self._indents = []

    def getsection(self):
        return self._section

    def section(self, section):
        '''
        Set the section of the file where to append code.
        Allows to make different sections in the file to append
        to in any order
        '''
        while len(self._lines) <= section:
            self._lines.append([])
        while len(self._indents) <= section:
            self._indents.append(0)
        self._section = section

    def getindent(self):
        '''
        returns indentation of the current section
        '''
        return self._indents[self._section]

    def setindent(self, indent):
        '''
        sets indentation of the current section
        '''
        self._indents[self._section] = indent;

    def indent_block(self):
        class Indenter(object):
            def __init__(self, sf):
                self.sf = sf
            def __enter__(self):
                self.sf.indent()
            def __exit__(self, type, value, traceback):
                self.sf.unindent()
        return Indenter(self)

    def indent(self):
        '''
        adds one level of indentation to the current section
        '''
        self._indents[self._section] += 1

    def unindent(self):
        '''
        removes one level of indentation to the current section
        '''
        assert self.getindent() > 0, "negative indent"
        self._indents[self._section] -= 1

    def __call__(self, fmt, *args):
        '''
        Append a line to the file at in its current section and
        indentation of the current section
        '''
        indent = SourceFile._one_indent_level * self._indents[self._section]
        self._lines[self._section].append(indent + (fmt % args))


    def writeout(self, path):
        with open(path, 'w') as f:
            for section in self._lines:
                for line in section:
                    print(line.rstrip(), file=f)


# FFI source file
_f = SourceFile()

# Rust interface file
_r = SourceFile()

# utility to add same code in both files
def _rf(fmt, *args):
    _f(fmt, *args)
    _r(fmt, *args)


_ns = None
_ext_names = {}

# global variable to keep track of serializers and
# switch data types due to weird dependencies
finished_serializers = []
finished_sizeof = []
finished_switch = []

_types_uneligible_to_copy = []

# current handler is used for error reporting
current_handler = None

# Keep tracks of types that have lifetime parameter
# Initialized with types that are defined in one module and used in other modules
types_with_lifetime = [
    "xcb_str_iterator_t",                   # defined in xproto, used in render
    "xcb_xv_image_format_info_iterator_t"   # defined in xv, used in xvmc
]

# link exceptions
link_exceptions = {
    "bigreq": "xcb",
    "xc_misc": "xcb"
}


#type translation
_ffi_type_translation = {
    'BOOL': 'u8'
}
_rs_type_translation = {
    'BOOL': 'bool'
}

# struct with only simple fields are defined as typedef to the ffi struct (issue #7)
# this list adds exception to this behavior
_rs_typedef_exceptions = [
    # not strictly necessary has Setup has complex fields
    # however intent is clear: 'xproto::Setup' MUST use StructPtr
    'xproto::Setup'
]

# exported functions to xcbgen start by 'rs_'

# starting with opening and closing

def rs_open(module):
    '''
    Handles module open.
    module is a xcbgen.state.Module object
    '''
    global _ns
    _ns = module.namespace

    linklib = "xcb"
    if _ns.is_ext:
        linklib = 'xcb-' + _ns.header
        _ext_names[_ns.ext_name.lower()] = _ns.header
        for (n, h) in module.direct_imports:
            if h != 'xproto':
                _ext_names[n.lower()] = h

    if _ns.header in link_exceptions:
        linklib = link_exceptions[_ns.header]

    ext_id_name = _ffi_name(_ns.prefix + ('id',))

    _r.section(0)
    _f.section(0)
    _rf('// Generated automatically from %s by rs_client.py version %s.',
            _ns.file, os.getenv('CARGO_PKG_VERSION', 'undefined'))
    _rf('// Do not edit!')
    _rf('')

    _f('')
    _f('#![allow(improper_ctypes)]')
    _f('')
    _f('use ffi::base::*;')

    if _ns.is_ext:
        for (n, h) in module.imports:
            _f('use ffi::%s::*;', _module_name(n))
        _f('')
    _f('use libc::{c_char, c_int, c_uint, c_void};')
    _f('use std;')
    _f('')

    _f.section(1)
    _f('')
    _f('')
    _f('#[link(name="%s")]', linklib)
    _f('extern {')
    _f.indent()
    if _ns.is_ext:
        _f('')
        _f('pub static mut %s: xcb_extension_t;', ext_id_name)


    _r('#![allow(unused_unsafe)]')
    _r('')
    _r('use base;')
    if _ns.is_ext:
        for (n, h) in module.imports:
            _r('use %s;', _module_name(n))
    _r('use ffi::base::*;')
    _r('use ffi::%s::*;', _module_name(_ns.ext_name))
    if _ns.is_ext:
        for (n, h) in module.imports:
            _r('use ffi::%s::*;', _module_name(n))
    _r('use libc::{self, c_char, c_int, c_uint, c_void};')
    _r('use std;')
    _r('use std::iter::Iterator;')
    _r('')
    if _ns.is_ext:
        _r('')
        _r("pub fn id() -> &'static mut base::Extension {")
        _r('    unsafe {')
        _r('        &mut %s', ext_id_name)
        _r('    }')
        _r('}')

    _r.section(1)
    _r('')
    _r('')



    if _ns.is_ext:
        _f.section(0)
        _f('')
        _f('pub const %s: u32 = %s;',
                    _ffi_const_name(('xcb', _ns.ext_name, 'major', 'version')),
                    _ns.major_version)
        _f('pub const %s: u32 = %s;',
                    _ffi_const_name(('xcb', _ns.ext_name, 'minor', 'version')),
                    _ns.minor_version)

        _r.section(0)
        _r('')
        _r('pub const MAJOR_VERSION: u32 = %s;', _ns.major_version)
        _r('pub const MINOR_VERSION: u32 = %s;', _ns.minor_version)



    EnumCodegen.build_collision_table(module)




def rs_close(module):
    '''
    Handles module close.
    module is a xcbgen.state.Module object.
    main task is to write the files out
    '''

    _f.section(1)

    _f('')
    _f.unindent()
    _f('} // extern')

    _f.writeout(os.path.join(module.rs_srcdir, "ffi", "%s.rs" % _module_name(_ns.ext_name)))
    _r.writeout(os.path.join(module.rs_srcdir, "%s.rs" % _module_name(_ns.ext_name)))



# transformation of name tuples

_cname_re = re.compile('([A-Z0-9][a-z]+|[A-Z0-9]+(?![a-z])|[a-z]+)')
_rs_keywords = ['type', 'str', 'match', 'new']


def _tit_split(string):
    '''
    splits string with '_' on each titlecase letter
    >>> _tit_split('SomeString')
    Some_String
    >>> _tit_split('WINDOW')
    WINDOW
    '''
    split = _cname_re.finditer(string)
    name_parts = [match.group(0) for match in split]
    return '_'.join(name_parts)

def _tit_cap(string):
    '''
    capitalize each substring beggining by a titlecase letter
    >>> _tit_cap('SomeString')
    SomeString
    >>> _tit_cap('WINDOW')
    Window
    '''
    split = _cname_re.finditer(string)
    name_parts = [match.group(0) for match in split]
    name_parts = [i[0].upper() + i[1:].lower() for i in name_parts]
    return ''.join(name_parts)


_extension_special_cases = ['XPrint', 'XCMisc', 'BigRequests']

def _module_name(name):
    if len(name):
        if name in _extension_special_cases:
            return _tit_split(name).lower()
        else:
            return name.lower()
    else:
        return 'xproto'


def _symbol(string):
    if string in _rs_keywords:
        string += '_'
    return string

def _upper_1st(string):
    '''
    return copy of string with first letter turned into upper.
    Other letters are untouched.
    '''
    if len(string) == 0:
        return ''
    if len(string) == 1:
        return string.upper()
    return string[0].upper() + string[1:]

def _upper_name(nametup):
    '''
    return a string made from a nametuple with all upper case
    joined with underscore
    >>> _upper_name(('xcb', 'constant', 'AwesomeValue'))
    XCB_CONSTANT_AWESOME_VALUE
    '''
    return '_'.join(tuple(_tit_split(name) for name in nametup)).upper()

def _cap_name(nametup):
    '''
    return a string made from a nametuple with joined title case
    >>> _cap_name(('xcb', 'Type', 'Name'))
    XcbTypeName
    >>> _cap_name(('xcb', 'TypeName'))
    XcbTypeName
    >>> _cap_name(('xcb', 'TYPENAME'))
    XcbTypename
    '''
    return ''.join(tuple(_upper_1st(name) for name in nametup))

def _lower_name(nametup):
    '''
    return a string made from a nametuple with all lower case
    joined with underscore
    >>> _upper_name(('xcb', 'Ext', 'RequestName'))
    xcb_ext_request_name
    '''
    return '_'.join(tuple(_tit_split(name) for name in nametup)).lower()


def _ext_nametup(nametup):
    '''
    return the nametup with 2nd name lowered if module is an extension
    >>> _ext_nametup(('u32',))
    ('u32',)
    >>> _ext_nametup(('xcb', 'XprotoType'))
    ('xcb', 'XprotoType')
    >>> _ext_nametup(('xcb', 'RandR', 'SuperType'))
    ('xcb', 'randr', 'SuperType')
    '''
    if len(nametup) > 2 and nametup[1].lower() in _ext_names:
        #nametup = tuple(_ext_names[name.lower()] if i == 1 else name
        #        for (i, name) in enumerate(nametup))
        # lowers extension to avoid '_' split with title letters
        nametup = tuple(_module_name(name) if i == 1 else name
                for (i, name) in enumerate(nametup))
    return nametup

def _ffi_type_name(nametup):
    '''
    turns the nametup into a FFI type
    >>> _ffi_type_name(('u32',))
    u32
    >>> _ffi_type_name(('xcb', 'XprotoType'))
    xcb_xproto_type_t
    >>> _ffi_type_name(('xcb', 'RandR', 'SuperType'))
    xcb_randr_super_type_t
    '''
    if len(nametup) == 1:
        # handles SimpleType
        if nametup[0] in _ffi_type_translation:
            return _ffi_type_translation[nametup[0]]
        return nametup[0]
    return _ffi_name(nametup + ('t',))


def _ffi_name(nametup):
    '''
    turns the nametup into a FFI name
    >>> _ffi_type_name(('u32',))
    u32
    >>> _ffi_type_name(('xcb', 'XprotoType', 't'))
    xcb_xproto_type_t
    >>> _ffi_type_name(('xcb', 'RandR', 'SuperType', 't'))
    xcb_randr_super_type_t
    '''
    secondIsExt = (len(nametup) > 2 and nametup[1].lower() in _ext_names)
    nametup = _ext_nametup(nametup)

    if secondIsExt:
        return '_'.join(tuple(name if i==1 else _tit_split(name)
                for (i, name) in enumerate(nametup))).lower()
    else:
        return '_'.join(tuple(_tit_split(name) for name in nametup)).lower()


def _ffi_const_name(nametup):
    return _ffi_name(_ext_nametup(nametup)).upper()


def _rs_extract_module(nametup):
    '''
    returns the module extracted from nametup
    along with the nametup without the module parts
    if module is local module, an empty module is returned
    >>> _rs_extract_module(('u32',))
    ("", "u32")
    >>> _rs_extract_module(('xcb', 'Type'))
    ("", ("Type"))
    >>> _rs_extract_module(('xcb', 'RandR', 'SuperType'))
    ("randr::", ("SuperType"))
    '''
    # handles SimpleType
    if len(nametup) == 1:
        return ("", nametup[0])

    # remove 'xcb'
    if nametup[0].lower() == 'xcb':
        nametup = nametup[1:]

    module = ''
    # handle extension type
    if nametup[0].lower() in _ext_names:
        ext = _ext_names[nametup[0].lower()]
        if (not _ns.is_ext or
                ext != _ns.header):
            module = ext + '::'
        nametup = nametup[1:]

    # handle xproto type for extensions
    else:
        if _ns.is_ext:
            module = 'xproto::'

    return (module, nametup)



def _rs_type_name(nametup):
    '''
    turns the nametup into a Rust type name
    foreign rust type names include module prefix
    >>> _rs_type_name(('u32',))
    u32
    >>> _rs_type_name(('xcb', 'Type'))
    xproto::Type
    >>> _rs_type_name(('xcb', 'RandR', 'SuperType'))
    randr::SuperType
    '''
    if len(nametup) == 1:
        if nametup[0] in _rs_type_translation:
            return _rs_type_translation[nametup[0]]
        return nametup[0]

    (module, nametup) = _rs_extract_module(nametup)

    return module + ''.join([_tit_cap(n) for n in nametup])


def _rs_name(nametup):

    (module, nametup) = _rs_extract_module(nametup)

    return module + '_'.join([_tit_split(n) for n in nametup]).lower()


def _rs_const_name(nametup):
    return _upper_name(_rs_extract_module(nametup)[1])

def _rs_field_name(string):
    res = ''
    for c in string:
        if c.isupper():
            res = res + '_' + c.lower()
        else:
            res = res + c
    return res


def _set_type_lifetime(typeobj, has_lifetime):
    typeobj.has_lifetime = has_lifetime

    # handle successive calls to _set_type_lifetime on the same object
    def ensure_in(val):
        if not val in types_with_lifetime:
            types_with_lifetime.append(val)

    def ensure_out(val):
        while val in types_with_lifetime:
            types_with_lifetime.remove(val)

    if has_lifetime:
        ensure_in(typeobj.ffi_iterator_type)
        ensure_in(typeobj.rs_type)
        ensure_in(typeobj.rs_iterator_type)
    else:
        ensure_out(typeobj.ffi_iterator_type)
        ensure_out(typeobj.rs_type)
        ensure_out(typeobj.rs_iterator_type)



# FFI codegen functions

def _ffi_type_setup(typeobj, nametup, suffix=()):
    '''
    Sets up all the C-related state by adding additional data fields to
    all Field and Type objects.  Here is where we figure out most of our
    variable and function names.

    Recurses into child fields and list member types.
    '''
    # Do all the various names in advance
    typeobj.ffi_type = _ffi_type_name(nametup + suffix)

    typeobj.ffi_iterator_type = _ffi_type_name(nametup + ('iterator',))
    typeobj.ffi_next_fn = _ffi_name(nametup + ('next',))
    typeobj.ffi_end_fn = _ffi_name(nametup + ('end',))

    typeobj.ffi_request_fn = _ffi_name(nametup)
    typeobj.ffi_checked_fn = _ffi_name(nametup + ('checked',))
    typeobj.ffi_unchecked_fn = _ffi_name(nametup + ('unchecked',))
    typeobj.ffi_reply_fn = _ffi_name(nametup + ('reply',))
    typeobj.ffi_reply_type = _ffi_type_name(nametup + ('reply',))
    typeobj.ffi_cookie_type = _ffi_type_name(nametup + ('cookie',))
    typeobj.ffi_reply_fds_fn = _ffi_name(nametup + ('reply_fds',))

    typeobj.ffi_need_aux = False
    typeobj.ffi_need_serialize = False
    typeobj.ffi_need_sizeof = False

    typeobj.ffi_aux_fn = _ffi_name(nametup + ('aux',))
    typeobj.ffi_aux_checked_fn = _ffi_name(nametup + ('aux', 'checked'))
    typeobj.ffi_aux_unchecked_fn = _ffi_name(nametup + ('aux', 'unchecked'))
    typeobj.ffi_serialize_fn = _ffi_name(nametup + ('serialize',))
    typeobj.ffi_unserialize_fn = _ffi_name(nametup + ('unserialize',))
    typeobj.ffi_unpack_fn = _ffi_name(nametup + ('unpack',))
    typeobj.ffi_sizeof_fn = _ffi_name(nametup + ('sizeof',))

    # special case: structs where variable size fields are followed
    # by fixed size fields
    typeobj.ffi_var_followed_by_fixed_fields = False

    if not typeobj.fixed_size():
        if not typeobj in _types_uneligible_to_copy:
            _types_uneligible_to_copy.append(typeobj)
        if hasattr(typeobj, 'parents'):
            for p in typeobj.parents:
                _types_uneligible_to_copy.append(p)


    if typeobj.is_container:

        prev_varsized_field = None
        prev_varsized_offset = 0
        first_field_after_varsized = None

        for field in typeobj.fields:
            _ffi_type_setup(field.type, field.field_type, ())
            if field.type.is_list:
                _ffi_type_setup(field.type.member, field.field_type, ())
                if (field.type.nmemb is None):
                    typeobj.ffi_need_sizeof = True

            field.ffi_field_type = _ffi_type_name(field.field_type)
            field.ffi_field_name = _symbol(field.field_name)
            field.has_subscript = (field.type.nmemb and
                            field.type.nmemb > 1)
            field.ffi_need_const = (field.type.nmemb != 1)
            field.ffi_need_pointer = (field.type.nmemb != 1)

            # correct the need_pointer field for variable size non-list types
            if not field.type.fixed_size():
                field.ffi_need_pointer = True
            if field.type.is_list and not field.type.member.fixed_size():
                field.ffi_need_pointer = True

            if field.type.is_switch:
                field.ffi_need_const = True
                field.ffi_need_pointer = True
                field.ffi_need_aux = True
            elif not field.type.fixed_size() and not field.type.is_bitcase:
                typeobj.ffi_need_sizeof = True

            field.ffi_iterator_type = _ffi_type_name(
                    field.field_type + ('iterator',))
            field.ffi_iterator_fn = _ffi_name(
                    nametup + (field.field_name, 'iterator'))
            field.ffi_accessor_fn = _ffi_name(
                    nametup + (field.field_name,))
            field.ffi_length_fn = _ffi_name(
                    nametup + (field.field_name, 'length'))
            field.ffi_end_fn = _ffi_name(
                    nametup + (field.field_name, 'end'))

            field.prev_varsized_field = prev_varsized_field
            field.prev_varsized_offset = prev_varsized_offset

            if prev_varsized_offset == 0:
                first_field_after_varsized = field
            field.first_field_after_varsized = first_field_after_varsized

            if field.type.fixed_size():
                prev_varsized_offset += field.type.size
                # special case: intermixed fixed and variable size fields
                if (prev_varsized_field is not None and
                        not field.type.is_pad and field.wire):
                    if not typeobj.is_union:
                        typeobj.ffi_need_serialize = True
                        typeobj.ffi_var_followed_by_fixed_fields = True
            else:
                typeobj.last_varsized_field = field
                prev_varsized_field = field
                prev_varsized_offset = 0

            if typeobj.ffi_var_followed_by_fixed_fields:
                if field.type.fixed_size():
                    field.prev_varsized_field = None

    if typeobj.ffi_need_serialize:
        # when _unserialize() is wanted, create _sizeof() as well
        # for consistency reasons
        typeobj.ffi_need_sizeof = True

    if not typeobj.is_bitcase:
        if typeobj.ffi_need_serialize:
            if typeobj.ffi_serialize_fn not in finished_serializers:
                finished_serializers.append(typeobj.ffi_serialize_fn)
                #_ffi_serialize('serialize', typeobj)

                # _unpack() and _unserialize() are only needed
                # for special cases:
                #   switch -> unpack
                #   special cases -> unserialize
                if (typeobj.is_switch or
                        typeobj.ffi_var_followed_by_fixed_fields):
                    pass
                    #_ffi_serialize('unserialize', typeobj)

        if typeobj.ffi_need_sizeof:
            if typeobj.ffi_sizeof_fn not in finished_sizeof:
                if not _ns.is_ext or typeobj.name[:2] == _ns.prefix:
                    finished_sizeof.append(typeobj.ffi_sizeof_fn)
                    #_ffi_serialize('sizeof', typeobj)




def _ffi_bitcase_name(switch, bitcase):
    assert switch.is_switch and bitcase.type.has_name
    switch_name = _lower_name(_ext_nametup(switch.name))
    return '_%s__%s' % (switch_name, bitcase.ffi_field_name)


def _ffi_struct(typeobj, must_pack=False):
    '''
    Helper function for handling all structure types.
    Called for structs, requests, replies, events, errors...
    '''

    struct_fields = []

    for field in typeobj.fields:
        if (not field.type.fixed_size()
            and not typeobj.is_switch
            and not typeobj.is_union):
            continue
        if field.wire:
            struct_fields.append(field)

    _f.section(0)
    _f('')
    _write_doc_brief_desc(_f, typeobj.doc)
    _f('#[repr(C%s)]', ', packed' if must_pack else '')
    _f('pub struct %s {', typeobj.ffi_type)
    _f.indent()

    maxfieldlen = 0
    if not typeobj.is_switch:
        for field in typeobj.fields:
            maxfieldlen = max(maxfieldlen, len(field.ffi_field_name))
    else:
        for b in typeobj.bitcases:
            if b.type.has_name:
                maxfieldlen = max(maxfieldlen, len(b.ffi_field_name))
            else:
                for field in b.type.fields:
                    maxfieldlen = max(maxfieldlen, len(field.ffi_field_name))



    def _ffi_struct_field(field):
        ftype = field.ffi_field_type
        space = ' '* (maxfieldlen - len(field.ffi_field_name))
        if (field.type.fixed_size() or typeobj.is_union or
            # in case of switch with switch children,
            # don't make the field a pointer
            # necessary for unserialize to work
            (typeobj.is_switch and field.type.is_switch)):
            if field.has_subscript:
                ftype = '[%s; %d]' % (ftype, field.type.nmemb)
            _f('pub %s: %s%s,', field.ffi_field_name, space, ftype)
        else:
            assert not field.has_subscript
            _f('pub %s: %s*mut %s,', field.ffi_field_name, space, ftype)

    named_bitcases = []

    if not typeobj.is_switch:
        for field in struct_fields:
            for d in typeobj.doc.fields[field.field_name]:
                _f('/// %s', d)
            _ffi_struct_field(field)
    else:
        for b in typeobj.bitcases:
            if b.type.has_name:
                named_bitcases.append(b)
                space = ' ' * (maxfieldlen - len(b.ffi_field_name))
                _f('pub %s: %s%s,', b.ffi_field_name, space,
                        _ffi_bitcase_name(typeobj, b))
            else:
                for field in b.type.fields:
                    _ffi_struct_field(field)

    _f.unindent()
    _f('}')
    if not typeobj in _types_uneligible_to_copy:
        _f('')
        _f('impl Copy for %s {}', typeobj.ffi_type)
        _f('impl Clone for %s {', typeobj.ffi_type)
        _f('    fn clone(&self) -> %s { *self }', typeobj.ffi_type)
        _f('}')

    for b in named_bitcases:
        _f('')
        _f('#[repr(C)]')
        _f('pub struct %s {', _ffi_bitcase_name(typeobj, b))
        _f.indent()
        maxfieldlen = 0
        for field in b.type.fields:
            maxfieldlen = max(maxfieldlen, len(field.ffi_field_name))
        for field in b.type.fields:
            _ffi_struct_field(field)
        _f.unindent()
        _f('}')



def _ffi_accessors_list(typeobj, field):
    '''
    Declares the accessor functions for a list field.
    Declares a direct-accessor function only if the list members
        are fixed size.
    Declares length and get-iterator functions always.
    '''

    list = field.type
    ffi_type = typeobj.ffi_type

    # special case: switch
    # in case of switch, 2 params have to be supplied to certain
    # accessor functions:
    #   1. the anchestor object (request or reply)
    #   2. the (anchestor) switch object
    # the reason is that switch is either a child of a request/reply
    # or nested in another switch,
    # so whenever we need to access a length field, we might need to
    # refer to some anchestor type
    switch_obj = typeobj if typeobj.is_switch else None
    if typeobj.is_bitcase:
        switch_obj = typeobj.parents[-1]
    if switch_obj is not None:
        ffi_type = switch_obj.ffi_type

    params = []
    parents = typeobj.parents if hasattr(typeobj, 'parents') else [typeobj]
    # 'R': parents[0] is always the 'toplevel' container type
    params.append(('R: *const %s' % parents[0].ffi_type, parents[0]))
    # auxiliary object for 'R' parameters
    R_obj = parents[0]

    if switch_obj is not None:
        # now look where the fields are defined that are needed to evaluate
        # the switch expr, and store the parent objects in accessor_params and
        # the fields in switch_fields

        # 'S': name for the 'toplevel' switch
        toplevel_switch = parents[1]
        params.append(('S: *const %s' % toplevel_switch.ffi_type,
                toplevel_switch))

        # auxiliary object for 'S' parameter
        S_obj = parents[1]

    _f.section(1)
    if list.member.fixed_size():
        idx = 1 if switch_obj is not None else 0
        _f('')
        _f('pub fn %s (%s)', field.ffi_accessor_fn, params[idx][0])
        _f('        -> *mut %s;', field.ffi_field_type)

    def _may_switch_fn(fn_name, return_type):
        _f('')
        has_lifetime = return_type in types_with_lifetime
        lifetime = "<'a>" if has_lifetime else ""
        if switch_obj is not None:
            fn_start = 'pub fn %s%s (' % (fn_name, lifetime)
            spacing = ' '*len(fn_start)
            _f('%sR: *const %s,', fn_start, R_obj.ffi_type)
            _f('%sS: *const %s)', spacing, S_obj.ffi_type)
            _f('        -> %s%s;', return_type, lifetime)
        else:
            _f('pub fn %s%s (R: *const %s)', fn_name, lifetime, ffi_type)
            _f('        -> %s%s;', return_type, lifetime)

    _may_switch_fn(field.ffi_length_fn, 'c_int')

    if field.type.member.is_simple:
        _may_switch_fn(field.ffi_end_fn, 'xcb_generic_iterator_t')
    else:
        _may_switch_fn(field.ffi_iterator_fn, field.ffi_iterator_type)



def _ffi_accessors_field(typeobj, field):
    '''
    Declares the accessor functions for a non-list field that follows
    a variable-length field.
    '''
    ffi_type = typeobj.ffi_type

    # special case: switch
    switch_obj = typeobj if typeobj.is_switch else None
    if typeobj.is_bitcase:
        switch_obj = typeobj.parents[-1]
    if switch_obj is not None:
        ffi_type = switch_obj.ffi_type

    _f.section(1)
    if field.type.is_simple:
        _f('')
        _f('pub fn %s (R: *const %s)', field.ffi_accessor_fn, ffi_type)
        _f('        -> %s;', field.ffi_field_type)
    else:
        if field.type.is_switch and switch_obj is None:
            return_type = '*mut c_void'
        else:
            return_type = '*mut %s' % field.ffi_field_type

        _f('')
        _f('pub fn %s (R: *const %s)', field.ffi_accessor_fn, ffi_type)
        _f('        -> %s;', return_type)


def _ffi_accessors(typeobj, nametup):
    for field in typeobj.fields:
        if not field.type.is_pad:
            if field.type.is_list and not field.type.fixed_size():
                _ffi_accessors_list(typeobj, field)
            elif (field.prev_varsized_field is not None
                    or not field.type.fixed_size()):
                _ffi_accessors_field(typeobj, field)


def _ffi_iterator(typeobj, nametup):

    has_lifetime = typeobj.ffi_iterator_type in types_with_lifetime
    lifetime = "<'a>" if has_lifetime else ""

    _f.section(0)
    _f('')
    _f('#[repr(C)]')
    _f("pub struct %s%s {", typeobj.ffi_iterator_type, lifetime)
    _f('    pub data:  *mut %s,', typeobj.ffi_type)
    _f('    pub rem:   c_int,')
    _f('    pub index: c_int,')
    if has_lifetime:
        _f("    _phantom:  std::marker::PhantomData<&'a %s>,", typeobj.ffi_type)
    _f('}')

    _f.section(1)
    _f('')
    _f('pub fn %s (i: *mut %s);', typeobj.ffi_next_fn,
            typeobj.ffi_iterator_type)

    _f('')
    _f('pub fn %s (i: *mut %s)', typeobj.ffi_end_fn,
            typeobj.ffi_iterator_type)
    _f('        -> xcb_generic_iterator_t;')




def _ffi_reply(request):
    '''
    Declares the function that returns the reply structure.
    '''
    _f.section(1)
    _f('')
    _f('/// the returned value must be freed by the caller using ' +
            'libc::free().')
    fn_start = 'pub fn %s (' % request.ffi_reply_fn
    spacing = ' ' * len(fn_start)
    _f('%sc:      *mut xcb_connection_t,', fn_start)
    _f('%scookie: %s,', spacing, request.ffi_cookie_type)
    _f('%serror:  *mut *mut xcb_generic_error_t)', spacing)
    _f('        -> *mut %s;', request.ffi_reply_type)


def _ffi_reply_has_fds(self):
    for field in self.fields:
        if field.isfd:
            return True
    return False


def _ffi_reply_fds(request, name):
    '''
    Declares the function that returns fds related to the reply.
    '''
    _f.section(1)
    _f('')
    _f('/// the returned value must be freed by the caller using ' +
            'libc::free().')
    fn_start = 'pub fn %s (' % request.ffi_reply_fds_fn
    spacing = ' ' * len(fn_start)
    _f('%sc:     *mut xcb_connection_t,', fn_start)
    _f('%sreply: *mut %s)', spacing, request.ffi_reply_type)
    _f('        -> *mut c_int;')



# Rust codegen function

def _rs_type_setup(typeobj, nametup, suffix=()):
    #assert typeobj.hasattr('ffi_type')

    typeobj.rs_type = _rs_type_name(nametup + suffix)

    if len(nametup) == 1:
        typeobj.rs_qualified_type = typeobj.rs_type
    else:
        module = _ns.ext_name.lower() if _ns.is_ext else 'xproto'
        typeobj.rs_qualified_type = '%s::%s' % (module, typeobj.rs_type)

    typeobj.rs_iterator_type = _rs_type_name(nametup+('iterator',))
    typeobj.rs_request_fn = _rs_name(nametup)
    typeobj.rs_checked_fn = _rs_name(nametup+('checked',))
    typeobj.rs_unchecked_fn = _rs_name(nametup+('unchecked',))

    typeobj.rs_aux_fn = _rs_name(nametup+('aux',))
    typeobj.rs_aux_checked_fn = _rs_name(nametup+('aux', 'checked'))
    typeobj.rs_aux_unchecked_fn = _rs_name(nametup+('aux', 'unchecked'))
    typeobj.rs_reply_type = _rs_type_name(nametup + ('reply',))
    typeobj.rs_cookie_type = _rs_type_name(nametup + ('cookie',))

    typeobj.rs_is_pod = False

    if typeobj.is_container:
        has_complex = False
        for field in typeobj.fields:
            _rs_type_setup(field.type, field.field_type)
            if field.type.is_list:
                _rs_type_setup(field.type.member, field.field_type)
            field.rs_field_name = _symbol(_rs_field_name(field.field_name))
            field.rs_field_type = _rs_type_name(field.field_type)

            field.rs_iterator_type = _rs_type_name(
                    field.field_type + ('iterator',))

            if not field.type.is_simple and not field.type.rs_is_pod \
                    and not field.type.is_pad:
                has_complex = True

        typeobj.rs_only_has_simple = not has_complex
        # we restrict POD a little
        typeobj.rs_is_pod = (
                (not has_complex) and
                (not typeobj.rs_qualified_type in _rs_typedef_exceptions) and
                (not typeobj.is_reply and not typeobj.is_union) and
                (not typeobj.is_switch))

        if typeobj.rs_is_pod:
            _set_type_lifetime(typeobj, False)



def _rs_struct(typeobj):
    _r.section(1)
    _r('')
    _write_doc_brief_desc(_r, typeobj.doc)
    if typeobj.rs_is_pod:
        _r('#[derive(Copy, Clone)]')
        _r('pub struct %s {', typeobj.rs_type)
        _r('    pub base: %s,', typeobj.ffi_type)
        _r('}')
    else:
        has_lifetime = typeobj.rs_type in types_with_lifetime
        lifetime1 = "<'a>" if has_lifetime else ""
        lifetime2 = "'a, " if has_lifetime else ""

        _r("pub type %s%s = base::StructPtr<%s%s>;", typeobj.rs_type, lifetime1,
                lifetime2, typeobj.ffi_type)


def _rs_accessors(typeobj):

    has_lifetime = typeobj.rs_type in types_with_lifetime
    lifetime = "<'a>" if has_lifetime else ""

    _r.section(1)
    _r('')
    _r('impl%s %s%s {', lifetime, typeobj.rs_type, lifetime)
    with _r.indent_block():
        if typeobj.rs_is_pod:
            # POD structs have a new method
            fnstart = 'pub fn new('
            fnspace = ' '*len(fnstart)
            argfields = []
            for f in typeobj.fields:
                if not f.type.is_pad:
                    argfields.append(f)
            maxfieldlen = 0
            for f in typeobj.fields:
                maxfieldlen = max(maxfieldlen, len(f.rs_field_name))
            if len(argfields):
                eol = ',' if len(argfields) > 1 else ')'
                f1 = argfields[0]
                space1 = ' '*(maxfieldlen - len(f1.rs_field_name))
                _r('#[allow(unused_unsafe)]')
                _r('%s%s: %s%s%s', fnstart, f1.rs_field_name, space1, f1.rs_field_type, eol)
                for (i, f) in enumerate(argfields[1:]):
                    argspace = ' '*(maxfieldlen-len(f.rs_field_name))
                    eol = ',' if i < len(argfields)-2 else ')'
                    _r('%s%s: %s%s%s', fnspace, f.rs_field_name, argspace, f.rs_field_type, eol)
                _r('        -> %s {', typeobj.rs_type)
            else:
                _r('#[allow(unused_unsafe)]')
                _r('%s) -> %s {', fnstart, typeobj.rs_type)

            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('%s {', typeobj.rs_type)
                    with _r.indent_block():
                        _r('base: %s {', typeobj.ffi_type)
                        with _r.indent_block():
                            for f in typeobj.fields:
                                space = ' '*(maxfieldlen-len(f.rs_field_name))
                                if f.type.rs_is_pod:
                                    _r('%s: %sstd::mem::transmute(%s),', f.rs_field_name, space, f.rs_field_name)
                                elif f.type.is_pad:
                                    fval = '0'
                                    if f.has_subscript:
                                        fval = '[0; %d]' % f.type.nmemb
                                    _r('%s: %s%s,', f.rs_field_name, space, fval)
                                else:
                                    assignment = f.rs_field_name
                                    if f.rs_field_type == 'bool':
                                        assignment = 'if %s { 1 } else { 0 }' % f.rs_field_name
                                    _r('%s: %s%s,', f.ffi_field_name, space, assignment)
                        _r('}')
                    _r('}')
                _r('}')
            _r('}')

        for (i, field) in enumerate(typeobj.fields):
            if field.visible and not field.type.is_switch:
                for d in typeobj.doc.fields[field.field_name]:
                    _r('/// %s', d)
                if typeobj.is_union:
                    _rs_union_accessor(typeobj, field)
                else:
                    _rs_accessor(typeobj, field)
    _r('}')


def _rs_reply_accessors(reply):
    '''
    same as _rs_accessors but handles fds special case
    '''
    has_lifetime = reply.rs_type in types_with_lifetime
    lifetime = "<'a>" if has_lifetime else ""

    fd_field = None
    nfd_field = None
    for f in reply.fields:
        if f.rs_field_name == 'nfd':
            nfd_field = f
        if f.isfd:
            fd_field = f

    reply_fields = []
    for f in reply.fields:
        if f.rs_field_name == 'nfd':
            # writing nfd field only if fds is not written
            if not fd_field or not nfd_field:
                reply_fields.append(f)
        elif not f.isfd:
            reply_fields.append(f)


    _r.section(1)
    _r('')
    _r('impl%s %s%s {', lifetime, reply.rs_type, lifetime)
    with _r.indent_block():
        # regular fields
        for field in reply_fields:
            if field.visible and not field.type.is_switch:
                _rs_accessor(reply, field)

        # fds field if any
        if nfd_field and fd_field:
            getter = reply.request.ffi_reply_fds_fn
            # adding 's'
            fname = fd_field.rs_field_name
            if not fname.endswith('s'):
                fname += 's'
            _r('pub fn %s(&self, c: &base::Connection) -> &[i32] {', fname)
            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('let nfd = (*self.ptr).nfd as usize;')
                    _r('let ptr = %s(c.get_raw_conn(), self.ptr);', getter)
                    _r('')
                    _r('std::slice::from_raw_parts(ptr, nfd)')
                _r('}')
            _r('}')
    _r('}')


def _rs_union_accessor(typeobj, field):
    if field.type.is_simple or field.type.rs_is_pod:
        _r('pub fn %s(&self) -> %s {', field.rs_field_name, field.rs_field_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                convert = ''
                if field.rs_field_type == 'bool':
                    convert = ' != 0'
                _r('let _ptr = self.data.as_ptr() as *const %s;', field.rs_field_type)
                _r('*_ptr%s', convert)
            _r('}')
        _r('}')
        _r('pub fn from_%s(%s: %s) -> %s {', field.rs_field_name,
                field.rs_field_name, field.rs_field_type, typeobj.rs_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                if field.rs_field_type == 'bool':
                    _r('let %s: %s = %s != 0;', field.rs_field_name,
                            field.ffi_field_type, field.rs_field_name)
                _r('let mut res = %s { data: [0; %d] };', typeobj.rs_type,
                        typeobj.union_num_bytes)
                _r('let res_ptr = res.data.as_mut_ptr() as *mut %s;', field.rs_field_type)
                _r('*res_ptr = %s;', field.rs_field_name)
                _r('res')
            _r('}')
        _r('}')


    elif field.type.is_list and field.type.fixed_size():
        assert (typeobj.union_num_bytes % field.type.size) == 0
        _r('pub fn %s(&self) -> &[%s] {',
                field.rs_field_name, field.rs_field_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r('let ptr = self.data.as_ptr() as *const %s;', field.rs_field_type)
                _r('std::slice::from_raw_parts(ptr, %d)',
                        typeobj.union_num_bytes / field.type.size)
            _r('}')
        _r('}')
        _r('pub fn from_%s(%s: [%s; %d]) -> %s {', field.rs_field_name,
                field.rs_field_name, field.rs_field_type,
                typeobj.union_num_bytes / field.type.size,
                typeobj.rs_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r('%s { data: std::mem::transmute(%s) }', typeobj.rs_type,
                        field.rs_field_name)
            _r('}')
        _r('}')


    elif field.type.is_container:
        if not field.type.rs_is_pod:
            _r('pub fn %s<\'a>(&\'a self) -> %s<\'a> {',
                    field.rs_field_name, field.rs_field_type)
        else:
            _r('pub fn %s(&self) -> %s {', field.rs_field_name, field.rs_field_type)

        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                if not field.type.rs_is_pod:
                    _r('std::mem::transmute(self)')
                else:
                    _r('let _ptr = self.data.as_ptr() as *const %s;', field.rs_field_type)
                    _r('*_ptr')
            _r('}')
        _r('}')



def _rs_accessor(typeobj, field, disable_pod_acc=False):
    if field.type.is_simple or field.type.rs_is_pod:
        _r('pub fn %s(&self) -> %s {', field.rs_field_name,
                field.rs_field_type)

        acc = '(*self.ptr)'
        if typeobj.rs_is_pod and not disable_pod_acc:
            acc = 'self.base'

        with _r.indent_block():
            convert = ''
            if field.rs_field_type == 'bool':
                convert = ' != 0'
            _r('unsafe {')
            with _r.indent_block():
                if field.type.rs_is_pod:
                    _r('std::mem::transmute(%s.%s)', acc, field.ffi_field_name)
                else:
                    _r('%s.%s%s', acc, field.ffi_field_name, convert)
            _r('}')
        _r('}')

    elif field.type.is_union:
        # do we already have a lifetime declared?
        has_lifetime = typeobj.rs_type in types_with_lifetime
        lifetime = "<'a>" if not has_lifetime else ""
        _r("pub fn %s%s(&'a self) -> &'a %s {", field.rs_field_name, lifetime,
                field.rs_field_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r('&(*self.ptr).%s', field.ffi_field_name)
            _r('}')
        _r('}')

    elif field.type.is_list and not field.type.fixed_size():
        if field.type.member.rs_type == 'bool':
            # special case for bool: we need to convert all elements into an owned vec
            _r('pub fn %s(&self) -> Vec<bool> {', field.rs_field_name)
            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('let field = self.ptr;')
                    _r('let len = %s(field);', field.ffi_length_fn)
                    _r('let data = %s(field);', field.ffi_accessor_fn)
                    _r('let slice = std::slice::from_raw_parts(data, len as usize);')
                    _r('slice.iter().map(|el| if *el == 0 {false} else{true}).collect()')
                _r('}')
            _r('}')
        elif field.type.member.is_simple:
            field_type = field.type.member.rs_type
            is_template = False
            if field_type == 'c_char':
                return_type = '&str'
            elif field_type == 'c_void':
                is_template = True
                return_type = '&[T]'
            else:
                return_type = '&[%s]' % field_type
            _r('pub fn %s%s(&self) -> %s {', field.rs_field_name,
                    '<T>' if is_template else '', return_type)
            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('let field = self.ptr;')
                    _r('let len = %s(field) as usize;', field.ffi_length_fn)
                    _r('let data = %s(field);', field.ffi_accessor_fn)
                    if field_type == 'c_char':
                        _r('let slice = ' +
                            'std::slice::from_raw_parts(' +
                                'data as *const u8, len);')
                        _r('// should we check what comes from X?')
                        _r('std::str::from_utf8_unchecked(&slice)')
                    elif is_template:
                        _r('debug_assert_eq!(len %% std::mem::size_of::<T>(), 0);')
                        _r('std::slice::from_raw_parts(data as *const T, ' +
                                'len / std::mem::size_of::<T>())')
                    else:
                        _r('std::slice::from_raw_parts(data, len)')
                _r('}')
            _r('}')
        else:
            lifetime = ""
            if field.rs_iterator_type in types_with_lifetime and \
                    typeobj.rs_type in types_with_lifetime:
                lifetime = "<'a>"
            _r('pub fn %s(&self) -> %s%s {',
                    field.rs_field_name, field.rs_iterator_type, lifetime)
            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('%s(self.ptr)', field.ffi_iterator_fn)
                _r('}')
            _r('}')
            pass

    elif field.type.is_list:
        _r('pub fn %s(&self) -> &[%s] {',
                field.rs_field_name, field.rs_field_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r('&(*self.ptr).%s', field.ffi_field_name)
            _r('}')
        _r('}')

    elif field.type.is_container:
        _r('pub fn %s(&self) -> %s {',
                field.rs_field_name, field.rs_field_type)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r('std::mem::transmute(&(*self.ptr).%s)',
                        field.ffi_field_name)
            _r('}')
        _r('}')

    elif not field.type.is_pad:
        raise Exception('did not treat accessor %s.%s'
                % (typeobj.ffi_type, field.ffi_field_name))



def _rs_iterator(typeobj):

    has_lifetime = typeobj.rs_iterator_type in types_with_lifetime
    lifetime1 = "<'a>" if has_lifetime else ""
    lifetime2 = "'a, " if has_lifetime else ""
    return_expr = '*data'
    if typeobj.rs_is_pod:
        return_expr = 'std::mem::transmute(*data)'
    elif typeobj.is_container and not typeobj.is_union:
        return_expr = 'std::mem::transmute(data)'

    _r.section(1)
    _r('')
    _r("pub type %s%s = %s%s;",
            typeobj.rs_iterator_type, lifetime1, typeobj.ffi_iterator_type, lifetime1)

    _r('')
    _r("impl%s Iterator for %s%s {", lifetime1, typeobj.rs_iterator_type, lifetime1)
    _r("    type Item = %s%s;", typeobj.rs_type, lifetime1)
    _r("    fn next(&mut self) -> std::option::Option<%s%s> {",
            typeobj.rs_type, lifetime1)
    _r('        if self.rem == 0 { None }')
    _r('        else {')
    _r('            unsafe {')
    _r('                let iter = self as *mut %s;',
            typeobj.ffi_iterator_type)
    _r('                let data = (*iter).data;')
    _r('                %s(iter);', typeobj.ffi_next_fn)
    _r('                Some(%s)', return_expr)
    _r('            }')
    _r('        }')
    _r('    }')
    _r('}')



def _rs_reply(request):

    _r.section(1)
    _r('')
    _r('pub type %s = base::Reply<%s>;', request.rs_reply_type, request.ffi_reply_type);




# Common codegen utilities

def _prepare_doc(typeobj):
    # preparing doc for easier handling
    # each typeobj must have a doc attribute with brief, description and fields

    def rework_phrase(phrase):
        # having 'unknown start of token' error by rustdoc sometimes.
        # This silents it
        # return phrase.replace('`', '')
        # Edit: not necessary anymore
        return phrase

    if hasattr(typeobj, "doc_prepared"):
        assert typeobj.doc_prepared == True
        return
    if hasattr(typeobj, "doc") and typeobj.doc:
        if typeobj.doc.brief:
            typeobj.doc.brief = [rework_phrase(p) for p in typeobj.doc.brief.split('\n')]
        else:
            typeobj.doc.brief = []
        if typeobj.doc.description:
            typeobj.doc.description = [rework_phrase(p) for p in typeobj.doc.description.split('\n')]
        else:
            typeobj.doc.description = []
        if hasattr(typeobj, "fields"):
            if not hasattr(typeobj.doc, "fields"):
                typeobj.doc.fields = {}
            for f in typeobj.fields:
                if f.field_name in typeobj.doc.fields:
                    typeobj.doc.fields[f.field_name] = \
                            [rework_phrase(p) for p in typeobj.doc.fields[f.field_name].split('\n')]
                else:
                    typeobj.doc.fields[f.field_name] = []
    else:
        class Doc(object): pass
        typeobj.doc = Doc()
        typeobj.doc.brief = []
        typeobj.doc.description = []
        typeobj.doc.fields = {}
        if hasattr(typeobj, "fields"):
            for f in typeobj.fields:
                typeobj.doc.fields[f.field_name] = []

    typeobj.doc_prepared = True


def _write_docs(sf, doclist):
    for s in doclist:
        sf('/// %s', s)


def _write_doc_brief_desc(sf, doc):
    _write_docs(sf, doc.brief)
    if len(doc.brief) and len(doc.description):
        sf('///')
    _write_docs(sf, doc.description)


class EnumCodegen(object):

    namecount = {}

    def build_collision_table(module):
        for v in module.types.values():
            key = _ffi_type_name(v[0])
            EnumCodegen.namecount[key] = (
                (EnumCodegen.namecount.get(key) or 0) + 1
            )


    def __init__(self, nametup, doc):
        self._nametup = nametup
        self._doc = doc

        self.done_vals = {}
        self.unique_discriminants = []
        self.conflicts = []
        self.all_discriminants = []
        key = _ffi_type_name(nametup)
        if EnumCodegen.namecount[key] > 1:
            nametup = nametup + ('enum',)
        self.ffi_name = _ffi_type_name(nametup)
        self.rs_name = _rs_type_name(nametup)


    def add_discriminant(self, name, val):
        class Discriminant: pass
        d = Discriminant()
        #d.rs_name = name
        d.rs_name = _rs_const_name(self._nametup+(name,))
        d.ffi_name = _ffi_const_name(self._nametup+(name,))
        d.valstr = '0x%02x' % val
        d.val = val
        d.doc = None
        if self._doc and name in self._doc.fields:
            d.doc = self._doc.fields[name]
        self.all_discriminants.append(d)
        if val in self.done_vals:
            self.conflicts.append(d)
        else:
            self.done_vals[val] = d
            self.unique_discriminants.append(d)


    def maxlen(self, name_field):
        maxnamelen = 0
        maxvallen = 0
        for d in self.unique_discriminants:
            maxvallen = max(maxvallen, len(d.valstr))
            maxnamelen = max(maxnamelen, len(getattr(d, name_field)))
        return (maxnamelen, maxvallen)


    def write_ffi(self):
        (maxnamelen, maxvallen) = self.maxlen('ffi_name')
        type_name = self.ffi_name
        _f.section(0)
        _f('')
        _write_doc_brief_desc(_f, self._doc)
        _f('pub type %s = u32;', type_name)
        for d in self.all_discriminants:
            d_name = d.ffi_name
            namespace = ' ' * (maxnamelen-len(d_name))
            valspace = ' ' * (maxvallen-len(d.valstr))
            if d.doc:
                ddocs = d.doc.split('\n')
                for dd in ddocs:
                    _f('/// %s', dd)
            _f('pub const %s%s: %s =%s %s;', d_name, namespace, type_name,
                    valspace, d.valstr)

    def write_rs(self):
        (maxnamelen, maxvallen) = self.maxlen("rs_name")
        _r.section(0)
        _r('')
        _write_doc_brief_desc(_r, self._doc)
        _r('pub type %s = u32;', self.rs_name)
        for d in self.all_discriminants:
            namespace = ' ' * (maxnamelen-len(d.rs_name))
            valspace = ' ' * (maxvallen-len(d.valstr))
            if d.doc:
                ddocs = d.doc.split('\n')
                for dd in ddocs:
                    _r('/// %s', dd)
            _r('pub const %s%s: %s =%s %s;', d.rs_name, namespace, self.rs_name,
                    valspace, d.valstr)





class RequestCodegen(object):

    def __init__(self, request):
        self.request = request

        self.void = False if self.request.reply else True

        self.ffi_cookie_type = ('xcb_void_cookie_t' if self.void
                else self.request.ffi_cookie_type)
        self.rs_cookie_type = ('base::VoidCookie' if self.void
                else self.request.rs_cookie_type)

        self.visible_fields = []
        for field in self.request.fields:
            if field.visible:
                self.visible_fields.append(field)

        # for, we do not filter out any visible field,
        # but we must find out if it is pointer, const ...
        self.ffi_params = []
        for field in self.visible_fields:
            self.ffi_params.append(field)


        # Rust is more complicated because of lists
        # here we pack lists in slices

        # there's basically 3 cases:
        # 1. regular fields, passed as-is to the ffi func
        # 2. masked lists (such as create_window event mask)
        #    given to rs slice of tuple (mask, value) and unpacked
        #    into int and pointer to ffi func
        # 3. regular lists, for which a length and a pointer
        #    must be passed to the ffi_func. these are given to
        #    rs by a slice

        # it happens to have 2 or more lists for same length field.
        # in this case, we will make 2 slices and runtime assert same length
        # eg: take a look at render::create_conical_gradient

        rs_num_template = 0
        template_letters = ['T', 'U', 'V', 'W']

        # xproto::send_event is special.
        # the FFI takes an event argument casted to a char*
        # here we are going to require an &Event<T> for the rs func
        self.rs_send_event = False
        if _ns.header == "xproto" and \
                self.request.rs_request_fn.startswith("send_event"):
            self.rs_send_event = True

        for f in self.visible_fields:
            f.rs_is_slice = False
            f.rs_template_let = ''
            f.rs_lenfield = None
            f.rs_is_mask_slice = False
            f.rs_maskfield = None
            f.rs_skip = False

        for (ffi_index, field) in enumerate(self.visible_fields):
            field.ffi_index = ffi_index

            if self.rs_send_event and field.rs_field_name == "event":
                field.rs_template_let = template_letters[rs_num_template]
                rs_num_template += 1

            elif field.type.is_list:

                if field.type.expr.bitfield:
                    # field associated with a mask
                    # eg. create_window last field
                    field.rs_is_mask_slice = True
                else:
                    # regular list with length and ptr
                    field.rs_is_slice = True
                    if field.type.member.rs_type == 'c_void':
                        field.rs_template_let = template_letters[rs_num_template]
                        rs_num_template += 1
                field.rs_lenfield = field.type.expr.lenfield
                if not field.rs_lenfield:
                    len_name = field.type.expr.lenfield_name
                    for f in self.visible_fields:
                        if f.field_name == len_name:
                            field.rs_lenfield = f
                # the mask is mandatory, but not the length (eg c strings)
                if field.rs_is_mask_slice:
                    assert field.rs_lenfield
                if field.rs_lenfield:
                    field.rs_lenfield.rs_skip = True

        self.rs_params = []

        for field in self.visible_fields:
            if not field.rs_skip:
                self.rs_params.append(field)

        self.rs_template = "<'a>"
        if rs_num_template:
            self.rs_template = "<'a"
            for i in range(rs_num_template):
                self.rs_template += ', ' + template_letters[i]
            self.rs_template += '>'

    def ffi_func_name(self, regular, aux):
        checked = self.void and not regular
        unchecked = not self.void and not regular

        if checked:
            func_name = (self.request.ffi_checked_fn if not aux else
                    self.request.ffi_aux_checked_fn)
        elif unchecked:
            func_name = (self.request.ffi_unchecked_fn if not aux else
                    self.request.ffi_aux_unchecked_fn)
        else:
            func_name = (self.request.ffi_request_fn if not aux else
                    self.request.ffi_aux_fn)

        return func_name



    def rs_func_name(self, regular, aux):
        checked = self.void and not regular
        unchecked = not self.void and not regular

        if checked:
            func_name = (self.request.rs_checked_fn if not aux else
                    self.request.rs_aux_checked_fn)
        elif unchecked:
            func_name = (self.request.rs_unchecked_fn if not aux else
                    self.request.rs_aux_unchecked_fn)
        else:
            func_name = (self.request.rs_request_fn if not aux else
                    self.request.rs_aux_fn)

        return func_name

    def ffi_rq_type(self, field, aux):
        ffi_rq_type = field.ffi_field_type
        if field.ffi_need_pointer:
            pointer = '*const ' if field.ffi_need_const else '*mut '
            ffi_rq_type = pointer + ffi_rq_type
        if field.type.ffi_need_serialize and not aux:
            ffi_rq_type = '*const c_void'
        return ffi_rq_type



    def write_ffi_rs(self, regular, aux=False):
        self.write_ffi(regular, aux)
        self.write_rs(regular, aux)


    def write_ffi(self, regular, aux=False):

        ffi_func_name = self.ffi_func_name(regular, aux)

        maxnamelen = 1
        for p in self.ffi_params:
            maxnamelen = max(maxnamelen, len(p.ffi_field_name))

        _f.section(1)
        _f("")
        _write_doc_brief_desc(_f, self.request.doc)
        fn_start = "pub fn %s (" % ffi_func_name
        func_spacing = ' ' * len(fn_start)
        spacing = " " * (maxnamelen-len('c'))
        eol = ',' if len(self.ffi_params) else ')'
        _f("%sc: %s*mut xcb_connection_t%s", fn_start, spacing, eol)

        for (i, p) in enumerate(self.ffi_params):
            ffi_rq_type = self.ffi_rq_type(p, aux)

            spacing = ' '*(maxnamelen-len(p.ffi_field_name))
            eol = ')' if i == (len(self.ffi_params)-1) else ','
            _f('%s%s: %s%s%s', func_spacing, p.ffi_field_name, spacing,
                    ffi_rq_type, eol)

        _f("        -> %s;", self.ffi_cookie_type)


    def write_rs(self, regular, aux=False):
        checked = (self.void and not regular) \
                or ((not self.void) and regular)
        rs_func_name = self.rs_func_name(regular, aux)
        ffi_func_name = self.ffi_func_name(regular, aux)

        maxnamelen = len('c')
        for p in self.rs_params:
            maxnamelen = max(maxnamelen, len(p.rs_field_name))

        let_lines = []
        call_params = []

        _r.section(1)
        _r('')
        _write_doc_brief_desc(_r, self.request.doc)
        doc_params = False
        for f in self.rs_params:
            if len(self.request.doc.fields[f.field_name]):
                doc_params = True
                break
        if doc_params:
            _r('///')
            _r('/// parameters:')
            _r('///')
            _r('///   - __c__:')
            _r('///       The connection object to the server')
            for f in self.rs_params:
                _r('///')
                _r('///   - __%s__:', f.field_name)
                for fd in self.request.doc.fields[f.field_name]:
                    _r('///       %s', fd)
        fn_start = "pub fn %s%s(" % (rs_func_name, self.rs_template)
        func_spacing = ' ' * len(fn_start)
        eol = ',' if len(self.rs_params) else ')'
        spacing = ' ' * (maxnamelen-len('c'))
        _r("%sc%s: &'a base::Connection%s", fn_start, spacing, eol)

        for (i, p) in enumerate(self.rs_params):

            ffi_rq_type = self.ffi_rq_type(p, aux)
            rs_typestr = p.rs_field_type

            if self.rs_send_event and p.rs_field_name == "event":
                rs_typestr = "&base::Event<%s>" % p.rs_template_let
                let_lines.append("let event_ptr = " +
                    "std::mem::transmute(event.ptr);")
                call_params.append((p.ffi_index, "event_ptr"))
                pass
            elif p.rs_is_mask_slice:

                maskfield = p.rs_lenfield
                rs_typestr = '&[(%s, %s)]' % (maskfield.rs_field_type,
                    p.rs_field_type)

                let_lines.append('let mut %s_copy = %s.to_vec();' %
                        (p.rs_field_name, p.rs_field_name))
                let_lines.append(('let (%s_mask, %s_vec) = ' +
                        'base::pack_bitfield(&mut %s_copy);') %
                        (p.rs_field_name, p.rs_field_name, p.rs_field_name))
                let_lines.append("let %s_ptr = %s_vec.as_ptr();" %
                        (p.rs_field_name, p.rs_field_name))

                # adding mask field if not already done
                # (already done should not happen with masks)
                if not next((cp for cp in call_params
                            if cp[0] == maskfield.ffi_index), None):
                    call_params.append((maskfield.ffi_index, "%s_mask as %s" %
                        (p.rs_field_name, maskfield.ffi_field_type)))

                # adding actual field
                call_params.append((p.ffi_index, '%s_ptr as %s' %
                        (p.rs_field_name, ffi_rq_type)))

            elif p.rs_is_slice:

                if p.type.member.rs_type == 'c_char':
                    rs_typestr = '&str'
                    let_lines.append('let %s = %s.as_bytes();' %
                            (p.rs_field_name, p.rs_field_name))
                elif p.type.member.rs_type == 'c_void':
                    rs_typestr = '&[%s]' % p.rs_template_let
                else:
                    rs_typestr = '&[%s]' % rs_typestr

                if p.rs_lenfield:
                    lenfield = p.rs_lenfield
                    # adding len field if not already done
                    # (already done can happen with lists)
                    if not next((cp for cp in call_params
                            if cp[0] == lenfield.ffi_index), None):
                        let_lines.append('let %s_len = %s.len();' %
                                (p.rs_field_name, p.rs_field_name))
                        call_params.append((lenfield.ffi_index,
                                "%s_len as %s" %
                                (p.rs_field_name, lenfield.ffi_field_type)))

                let_lines.append('let %s_ptr = %s.as_ptr();' %
                        (p.rs_field_name, p.rs_field_name))
                # adding actual field
                call_params.append((p.ffi_index, '%s_ptr as %s' %
                        (p.rs_field_name, ffi_rq_type)))

            elif p.type.is_container and p.ffi_need_pointer:
                rs_typestr = 'std::option::Option<%s>' % rs_typestr
                let_lines.append('let %s_ptr = match %s {' % (p.rs_field_name,
                        p.rs_field_name))
                let_lines.append('    Some(p) => p.ptr as %s,' %
                        ffi_rq_type)
                let_lines.append('    None => std::ptr::null()')
                let_lines.append('};')
                call_params.append((p.ffi_index, '%s_ptr' % p.rs_field_name))

            elif p.type.is_container and not p.type.rs_is_pod:
                call_params.append((p.ffi_index, '*(%s.ptr)' %
                        p.rs_field_name))

            elif p.type.rs_is_pod:
                call_params.append((p.ffi_index, '%s.base' %
                        p.rs_field_name))
            else:
                call_params.append((p.ffi_index,
                        '%s as %s' % (p.rs_field_name, ffi_rq_type)))

            spacing = ' ' * (maxnamelen-len(p.rs_field_name))
            eol = ',' if i < (len(self.rs_params)-1) else ')'
            _r('%s%s%s: %s%s', func_spacing, p.rs_field_name,
                    spacing, rs_typestr, eol)

        _r("        -> %s<'a> {", self.rs_cookie_type)

        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                for l in let_lines:
                    _r(l)

                call_start = 'let cookie = %s(' % ffi_func_name
                eol = ',' if len(call_params) else ');'
                spacing = ' ' * len(call_start)
                _r('%sc.get_raw_conn()%s', call_start, eol)

                call_params.sort(key=lambda x: x[0])

                for (i, (ffi_ind, p)) in enumerate(call_params):
                    eol = ',' if i < (len(call_params)-1) else ');'
                    _r('%s%s%s  // %d', spacing, p, eol, ffi_ind)

                _r("%s {", self.rs_cookie_type)
                _r("    cookie:  cookie,")
                _r("    conn:    c,")
                _r("    checked: %s", 'true' if checked else 'false')
                _r("}")
            _r('}')
        _r('}')




def _opcode(nametup, opcode):
    # handle GLX with -1 opcode
    optype = 'u8' if int(opcode) >= 0 else 'i8'

    ffi_name = _ffi_const_name(nametup)
    _f.section(0)
    _f('')
    _f('pub const %s: %s = %s;', ffi_name, optype, opcode)

    rs_name = _rs_const_name(nametup)
    _r.section(1)
    _r('')
    _r('pub const %s: %s = %s;', rs_name, optype, opcode)



def _cookie(request):
    _f.section(0)
    _f('')
    _f('#[derive(Copy, Clone)]')
    _f('#[repr(C)]')
    _f('pub struct %s {', request.ffi_cookie_type)
    _f('    sequence: c_uint')
    _f('}')

    _r.section(1)
    _r("")
    _r("pub type %s<'a> = base::Cookie<'a, %s>;",
            request.rs_cookie_type, request.ffi_cookie_type)

    cookie = request.rs_cookie_type
    reply = request.rs_reply_type
    func = request.ffi_reply_fn

    _r.section(1)
    _r('')
    _r("impl<'a> %s<'a> {", cookie)
    with _r.indent_block():
        _r("pub fn get_reply(&self) -> Result<%s, base::GenericError> {", reply)
        with _r.indent_block():
            _r('unsafe {')
            with _r.indent_block():
                _r("if self.checked {")
                _r("    let mut err: *mut xcb_generic_error_t = "
                        + "std::ptr::null_mut();")
                _r("    let reply = %s {", reply)
                _r("        ptr: %s (self.conn.get_raw_conn(), self.cookie, &mut err)", func)
                _r("    };")
                _r("    if err.is_null() { Ok (reply) }")
                _r("    else { Err(base::GenericError { ptr: err }) }")
                _r("} else {")
                _r("    Ok( %s {", reply)
                _r("        ptr: %s (self.conn.get_raw_conn(), self.cookie, ", func)
                _r("                std::ptr::null_mut())")
                _r("    })")
                _r("}")
            _r('}')
        _r('}')
    _r('}')




def _must_pack_event(event, nametup):
    # The generic event structure xcb_ge_event_t has the full_sequence field
    # at the 32byte boundary. That's why we've to inject this field into GE
    # events while generating the structure for them. Otherwise we would read
    # garbage (the internal full_sequence) when accessing normal event fields
    # there.
    must_pack = False
    if (hasattr(event, 'is_ge_event')
            and event.is_ge_event
            and event.name == nametup):
        event_size = 0
        for field in event.fields:
            if field.type.size != None and field.type.nmemb != None:
                event_size += field.type.size * field.type.nmemb
            if event_size == 32:
                full_sequence = Field(tcard32,
                        tcard32.name, 'full_sequence',
                        False, True, True)
                idx = event.fields.index(field)
                event.fields.insert(idx + 1, full_sequence)

                # If the event contains any 64-bit extended fields, they need
                # to remain aligned on a 64-bit boundary. Adding full_sequence
                # would normally break that; force the struct to be packed.
                must_pack = any(f.type.size == 8 and f.type.is_simple
                        for f in event.fields[(idx+1):])
                break

    return must_pack


def _handle_switch(typeobj, nametup):
    if typeobj.is_switch and typeobj.ffi_type not in finished_switch:
        finished_switch.append(typeobj.ffi_type)

        for bitcase in typeobj.bitcases:
            fname = _symbol(bitcase.field_name)
            bitcase.ffi_field_name = fname
            bitcase.rs_field_name = fname
            bitcase.nametup = (bitcase.field_type if bitcase.type.has_name
                    else nametup)
            _ffi_type_setup(bitcase.type, bitcase.nametup, ())
            _rs_type_setup(bitcase.type, bitcase.nametup, ())

        _set_type_lifetime(typeobj, True)

        _ffi_struct(typeobj)
        _rs_struct(typeobj)

        for bitcase in typeobj.bitcases:
            _ffi_accessors(bitcase.type, bitcase.nametup)
            # TODO: rs accessors

    if typeobj.is_container:
        for f in typeobj.fields:
            _prepare_doc(f.type)
            _handle_switch(f.type, f.field_type)


# codegen drivers

def rs_simple(simple, nametup):
    '''
    simple is SimpleType object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('simple:  ', nametup)

    _prepare_doc(simple)

    simple.has_lifetime = False

    _ffi_type_setup(simple, nametup)
    _f.section(0)
    assert len(simple.name) == 1
    _f('')
    _write_doc_brief_desc(_f, simple.doc)
    _f('pub type %s = %s;', simple.ffi_type, simple.name[0])
    _ffi_iterator(simple, nametup)

    _rs_type_setup(simple, nametup)
    _r.section(0)
    _r('')
    _write_doc_brief_desc(_r, simple.doc)
    _r('pub type %s = %s;', simple.rs_type, simple.ffi_type)



def rs_enum(typeobj, nametup):
    '''
    typeobj is xcbgen.xtypes.Enum object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('enum:    ', nametup)

    _prepare_doc(typeobj)

    ecg = EnumCodegen(nametup, typeobj.doc)

    val = -1
    for (enam, eval) in typeobj.values:
        val = int(eval) if eval != '' else val+1
        ecg.add_discriminant(enam, val)

    ecg.write_ffi()
    ecg.write_rs()




def rs_struct(struct, nametup):
    '''
    struct is Struct object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('struct:  ', nametup)

    _prepare_doc(struct)

    struct.has_lifetime = True

    _ffi_type_setup(struct, nametup)
    _rs_type_setup(struct, nametup)
    _handle_switch(struct, nametup)

    _set_type_lifetime(struct, struct.has_lifetime)

    _ffi_struct(struct)
    _ffi_accessors(struct, nametup)
    _ffi_iterator(struct, nametup)

    _rs_struct(struct)
    _rs_accessors(struct)
    _rs_iterator(struct)



def rs_union(union, nametup):
    '''
    union is Union object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('union:   ', nametup)

    _prepare_doc(union)

    union.has_lifetime = False

    _ffi_type_setup(union, nametup)
    _rs_type_setup(union, nametup)

    biggest = 1
    most_aligned = 1
    ptr_size = 8 if sys.maxsize > 2**32 else 4
    for field in union.fields:
        fs = ptr_size
        fa = ptr_size
        if field.type.size:
            fs = field.type.size
            fa = field.type.size
        if field.type.nmemb:
            fs = fa * field.type.nmemb
        biggest = max(biggest, fs)
        most_aligned = max(most_aligned, fa)

    assert biggest >= most_aligned

    num_aligned = int(biggest / most_aligned)
    if biggest % most_aligned:
        num_aligned += 1

    num_bytes = num_aligned * most_aligned
    union.union_num_bytes = num_bytes

    _f.section(0)
    _f('')
    _write_doc_brief_desc(_f, union.doc)
    _f('// union')
    _f('#[repr(C)]')
    _f('pub struct %s {', union.ffi_type)
    _f('    pub data: [u8; %d]', num_bytes)
    _f('}')

    _f('')
    _f('impl Copy for %s {}', union.ffi_type)
    _f('impl Clone for %s {', union.ffi_type)
    _f('    fn clone(&self) -> %s { *self }', union.ffi_type)
    _f('}')

    _ffi_iterator(union, nametup)

    _r.section(1)
    _r('')
    _r('pub type %s = %s;', union.rs_type, union.ffi_type)
    _rs_accessors(union)
    _rs_iterator(union)



def rs_request(request, nametup):
    '''
    request is Request object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('request: ', nametup)

    _prepare_doc(request)

    request.has_lifetime = False

    _ffi_type_setup(request, nametup, ('request',))
    _rs_type_setup(request, nametup, ('request',))
    _handle_switch(request, nametup)

    _set_type_lifetime(request, request.has_lifetime)

    rcg = RequestCodegen(request)

    _opcode(nametup, request.opcode)
    _ffi_struct(request)

    if request.reply:
        _prepare_doc(request.reply)
        # enable getting the request from the reply
        request.reply.request = request
        request.reply.has_lifetime = False

        _cookie(request)

        _ffi_type_setup(request.reply, nametup, ('reply',))
        _rs_type_setup(request.reply, nametup, ('reply',))
        _handle_switch(request.reply, nametup)

        _set_type_lifetime(request.reply, request.reply.has_lifetime)

        _ffi_struct(request.reply)
        _ffi_accessors(request.reply, nametup + ('reply',))
        _ffi_reply(request)
        if _ffi_reply_has_fds(request.reply):
            _ffi_reply_fds(request, nametup)

        _rs_reply(request)
        _rs_reply_accessors(request.reply)

    # regular call 'request_name'
    rcg.write_ffi_rs(True, False)
    # unregular call 'request_name_checked' or 'request_name_unchecked'
    # depending on cookie type
    rcg.write_ffi_rs(False, False)

    if request.ffi_need_aux:
        rcg.write_ffi_rs(True, True)
        rcg.write_ffi_rs(False, True)


def rs_event(event, nametup):
    '''
    event is Event object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('event:   ', nametup)

    must_pack = _must_pack_event(event, nametup)
    # _must_pack_event may insert fields,
    # therefore must be called before _prepare_doc
    _prepare_doc(event)

    if must_pack:
        print('event ', nametup, ' is packed')

    event.has_lifetime = False

    _ffi_type_setup(event, nametup, ('event',))
    _rs_type_setup(event, nametup, ('event',))

    _set_type_lifetime(event, event.has_lifetime)

    _opcode(nametup, event.opcodes[nametup])

    _r.section(1)
    _r('')
    _write_doc_brief_desc(_r, event.doc)
    _r('pub type %s = base::Event<%s>;', event.rs_type, event.ffi_type)

    if event.name == nametup:
        _ffi_struct(event, must_pack)

        accessor_fields = []
        for f in event.fields:
            if not f.visible: continue
            accessor_fields.append(f)
            if f.type.is_list or f.type.is_switch or f.type.is_bitcase:
                try:
                    accessor_fields.remove(f.type.expr.lenfield)
                except:
                    pass

        new_params = []
        if len(event.opcodes) > 1:
            new_params.append('response_type: u8')

        _r.section(1)
        _r('')
        _r('impl %s {', event.rs_type)
        with _r.indent_block():
            for f in accessor_fields:
                for fd in event.doc.fields[f.field_name]:
                    _r('/// %s', fd)
                _rs_accessor(event, f, True)

                rs_ftype = f.rs_field_type
                if f.has_subscript:
                    rs_ftype = "[%s; %d]" % (rs_ftype, f.type.nmemb)

                new_params.append("%s: %s" % (f.rs_field_name, rs_ftype))

            _r('/// Constructs a new %s', event.rs_type)
            if len(event.opcodes) > 1:
                _r('/// `response_type` must be set to one of:')
                for opname in event.opcodes:
                    _r('///     - `%s`', _rs_const_name(opname))
            else:
                _r('/// `response_type` will be set automatically to %s',
                        _rs_const_name(nametup))
            fn_start = "pub fn new("
            fn_space = ' ' * len(fn_start)
            p = new_params[0] if len(new_params) else ''
            eol = ',' if len(new_params)>1 else ')'
            _r('%s%s%s', fn_start, p, eol)
            for (i, p) in enumerate(new_params[1:]):
                eol = ',' if i != len(new_params)-2 else ')'
                _r("%s%s%s", fn_space, p, eol)

            _r('        -> %s {', event.rs_type)
            with _r.indent_block():
                _r('unsafe {')
                with _r.indent_block():
                    _r('let raw = libc::malloc(32 as usize) as *mut %s;',
                            event.ffi_type)
                    if len(event.opcodes) > 1:
                        # build list of possible opcodes
                        orlist = ' ||\n                    '.join(
                                [('response_type == %s' % _rs_const_name(opname))
                                    for opname in event.opcodes])
                        _r('assert!(%s,', orlist)
                        _r('        "wrong response_type supplied to %s::new");',
                                event.rs_type)
                        _r('(*raw).response_type = response_type;')
                    else:
                        _r('(*raw).response_type = %s;', _rs_const_name(nametup))
                    for f in event.fields:
                        if not f.visible: continue
                        if f.type.is_container and not f.type.is_union \
                                and not f.type.rs_is_pod:
                            _r('(*raw).%s = *%s.ptr;',
                                    f.ffi_field_name, f.rs_field_name)

                        elif f.type.rs_is_pod:
                            _r('(*raw).%s = %s.base;', f.ffi_field_name,
                                    f.rs_field_name)

                        else:
                            assignment = f.rs_field_name
                            if f.rs_field_type == 'bool':
                                assignment = ('if %s { 1 } else { 0 }' %
                                    f.rs_field_name)
                            _r('(*raw).%s = %s;', f.ffi_field_name, assignment)
                    _r('%s {', event.rs_type)
                    _r('    ptr: raw')
                    _r('}')
                _r('}')
            _r('}')
        _r('}')


    else:
        _f.section(0)
        _f('')
        _f('pub type %s = %s;', _ffi_type_name(nametup+('event',)),
                            _ffi_type_name(event.name+('event',)))



def rs_error(error, nametup):
    '''
    error is Error object
    nametup is a name tuple
    '''
    global current_handler
    current_handler = ('error:   ', nametup)

    _prepare_doc(error)

    _ffi_type_setup(error, nametup, ('error',))
    _opcode(nametup, error.opcodes[nametup])

    if error.name == nametup:
        _ffi_struct(error)
    else:
        _f.section(0)
        _f('')
        _f('pub type %s = %s;', _ffi_type_name(nametup+('error',)),
                            _ffi_type_name(error.name+('error',)))

    _rs_type_setup(error, nametup, ('error',))
    _r.section(0)
    _r('')
    _r('pub struct %s {', error.rs_type)
    _r('    pub base: base::Error<%s>', error.ffi_type)
    _r('}')


def usage(program):
    print('Usage: {} -o SRCDIR file.xml', program, file=sys.stderr)


if __name__ == '__main__':

    from optparse import OptionParser

    parser = OptionParser(usage="Usage: %prog -o SRCDIR file.xml")
    parser.add_option('-o', '--output', dest='srcdir', metavar='SRCDIR',
                help='specifies rust src dir where to generate files')

    (options, args) = parser.parse_args(sys.argv)

    if options.srcdir == None:
        parser.error('-o SRCDIR is mandatory')

    if not os.path.isdir(options.srcdir):
        parser.error('-o SRCDIR must be a directory')

    if len(args) < 2:
        parser.error('input XML file must be supplied')

    output = {  'open'      : rs_open,
                'close'     : rs_close,
                'simple'    : rs_simple,
                'enum'      : rs_enum,
                'struct'    : rs_struct,
                'union'     : rs_union,
                'request'   : rs_request,
                'event'     : rs_event,
                'error'     : rs_error }
    try:
        from xcbgen.state import Module
        from xcbgen.xtypes import *
    except ImportError:
        print('failed to load xcbgen', file=sys.stderr)
        raise

    # Parse the xml header
    module = Module(args[1], output)
    module.rs_srcdir = options.srcdir

    # Build type-registry and resolve type dependencies
    module.register()
    module.resolve()

    # Output the code
    try:
        module.generate()
    except:
        print('error occured in handler: ', current_handler, file=sys.stderr)
        raise