forked from rust-x-bindings/rust-xcb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rs_client.py
executable file
·2461 lines (1998 loc) · 79.8 KB
/
rs_client.py
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
#!/usr/bin/env python3
# Copyright (c) 2016 Remi Thebault <[email protected]>
#
# 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',))