-
Notifications
You must be signed in to change notification settings - Fork 2
/
patch_ctypes_changes_from_fork.diff
2198 lines (2010 loc) · 87.7 KB
/
patch_ctypes_changes_from_fork.diff
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
Index: lib/python/ctypes/ctypesgen.py
===================================================================
--- lib/python/ctypes/ctypesgen.py (revision 73073)
+++ lib/python/ctypes/ctypesgen.py (working copy)
@@ -93,6 +93,15 @@
default=None, help='regular expression for symbols to always include')
op.add_option('-x', '--exclude-symbols', dest='exclude_symbols',
default=None, help='regular expression for symbols to exclude')
+ op.add_option('', '--no-stddef-types', action='store_true',
+ dest='no_stddef_types', default=False,
+ help='Do not support extra C types from stddef.h')
+ op.add_option('', '--no-gnu-types', action='store_true',
+ dest='no_gnu_types', default=False,
+ help='Do not support extra GNU C types')
+ op.add_option('', '--no-python-types', action='store_true',
+ dest='no_python_types', default=False,
+ help='Do not support extra C types built in to Python')
# Printer options
op.add_option('', '--header-template', dest='header_template', default=None,
@@ -104,6 +113,9 @@
op.add_option('', '--insert-file', dest='inserted_files', default=[],
action='append', metavar='FILENAME',
help='Add the contents of FILENAME to the end of the wrapper file.')
+ op.add_option('', '--output-language', dest='output_language', metavar='LANGUAGE',
+ default='python',
+ help="Choose output language (`json' or `python' [default])")
# Error options
op.add_option('', "--all-errors", action="store_true", default=False,
@@ -135,6 +147,17 @@
if len(options.libraries) == 0:
msgs.warning_message('No libraries specified', cls='usage')
+ # Check output language
+ printer = None
+ if options.output_language == "python":
+ printer = ctypesgencore.printer.WrapperPrinter
+ elif options.output_language == "json":
+ printer = ctypesgencore.printer_json.WrapperPrinter
+ else:
+ msgs.error_message("No such output language `" +
+ options.output_language + "'", cls='usage')
+ sys.exit(1)
+
# Step 1: Parse
descriptions = ctypesgencore.parser.parse(options.headers, options)
Index: lib/python/ctypes/ctypesgencore/ctypedescs.py
===================================================================
--- lib/python/ctypes/ctypesgencore/ctypedescs.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/ctypedescs.py (working copy)
@@ -57,6 +57,19 @@
('va_list', True, 0): 'c_void_p',
}
+ctypes_type_map_python_builtin = {
+ ('int', True, 2): 'c_longlong',
+ ('int', False, 2): 'c_ulonglong',
+ ('size_t', True, 0): 'c_size_t',
+ ('apr_int64_t', True, 0): 'c_int64',
+ ('off64_t', True, 0): 'c_int64',
+ ('apr_uint64_t', True, 0): 'c_uint64',
+ ('wchar_t', True, 0): 'c_wchar',
+ ('ptrdiff_t', True, 0): 'c_ptrdiff_t', # Requires definition in preamble
+ ('ssize_t', True, 0): 'c_ptrdiff_t', # Requires definition in preamble
+ ('va_list', True, 0): 'c_void_p',
+}
+
# This protocol is used for walking type trees.
@@ -230,11 +243,31 @@
self.count.py_string(False))
+class CtypesNoErrorCheck(object):
+
+ def py_string(self):
+ return 'None'
+
+ def __bool__(self):
+ return False
+ __nonzero__ = __bool__
+
+
+class CtypesPointerCast(object):
+
+ def __init__(self, target):
+ self.target = target
+
+ def py_string(self):
+ return 'lambda v,*a : cast(v, {})'.format(self.target.py_string())
+
+
class CtypesFunction(CtypesType):
def __init__(self, restype, parameters, variadic=False):
CtypesType.__init__(self)
self.restype = restype
+ self.errcheck = CtypesNoErrorCheck()
# Don't allow POINTER(None) (c_void_p) as a restype... causes errors
# when ctypes automagically returns it as an int.
@@ -242,12 +275,17 @@
# you can make it any arbitrary type.
if isinstance(self.restype, CtypesPointer) and \
isinstance(self.restype.destination, CtypesSimple) and \
- self.restype.destination.name == 'None':
- self.restype = CtypesPointer(CtypesSpecial('c_void'), ())
+ self.restype.destination.name == 'void':
+ # we will provide a means of converting this to a c_void_p
+ self.restype = CtypesPointer(CtypesSpecial('c_ubyte'), ())
+ self.errcheck = CtypesPointerCast(CtypesSpecial('c_void_p'))
- # Return 'ReturnString' instead of simply 'String'
+ # Return "String" instead of "POINTER(c_char)"
if self.restype.py_string() == 'POINTER(c_char)':
- self.restype = CtypesSpecial('ReturnString')
+ if 'const' in self.restype.qualifiers:
+ self.restype = CtypesSpecial('c_char_p')
+ else:
+ self.restype = CtypesSpecial('String')
self.argtypes = [remove_function_pointer(p) for p in parameters]
self.variadic = variadic
@@ -273,9 +311,10 @@
class CtypesStruct(CtypesType):
- def __init__(self, tag, variety, members, src=None):
+ def __init__(self, tag, packed, variety, members, src=None):
CtypesType.__init__(self)
self.tag = tag
+ self.packed = packed
self.variety = variety # "struct" or "union"
self.members = members
Index: lib/python/ctypes/ctypesgencore/descriptions.py
===================================================================
--- lib/python/ctypes/ctypesgencore/descriptions.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/descriptions.py (working copy)
@@ -119,10 +119,11 @@
class StructDescription(Description):
"""Simple container class for a structure or union definition."""
- def __init__(self, tag, variety, members, opaque, ctype, src=None):
+ def __init__(self, tag, packed, variety, members, opaque, ctype, src=None):
Description.__init__(self, src)
# The name of the structure minus the "struct" or "union"
self.tag = tag
+ self.packed = packed
# A string "struct" or "union"
self.variety = variety
# A list of pairs of (name,ctype)
@@ -167,7 +168,7 @@
class FunctionDescription(Description):
"""Simple container class for a C function."""
- def __init__(self, name, restype, argtypes, variadic=False, src=None):
+ def __init__(self, name, restype, argtypes, errcheck, variadic=False, src=None):
Description.__init__(self, src)
# Name, a string
self.name = name
@@ -177,6 +178,8 @@
self.restype = restype
# A list of ctypes representing the argument types
self.argtypes = argtypes
+ # An optional error checker/caster
+ self.errcheck = errcheck
# Does this function accept a variable number of arguments?
self.variadic = variadic
Index: lib/python/ctypes/ctypesgencore/expressions.py
===================================================================
--- lib/python/ctypes/ctypesgencore/expressions.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/expressions.py (working copy)
@@ -7,7 +7,7 @@
'''
import keyword
-
+import sys
from .ctypedescs import *
@@ -84,10 +84,13 @@
neg_inf = ()
def py_string(self, can_be_ctype):
- if self.value == ConstantExpressionNode.pos_inf:
- return "float('inf')"
- elif self.value == ConstantExpressionNode.neg_inf:
- return "float('-inf')"
+ if (sys.platform != 'win32' or (sys.platform == 'win32' and
+ sys.version_info >= (2, 6))):
+ # Windows python did not get infinity support until 2.6
+ if self.value == ConstantExpressionNode.pos_inf:
+ return "float('inf')"
+ elif self.value == ConstantExpressionNode.neg_inf:
+ return "float('-inf')"
return repr(self.value)
Index: lib/python/ctypes/ctypesgencore/libraryloader.py
===================================================================
--- lib/python/ctypes/ctypesgencore/libraryloader.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/libraryloader.py (working copy)
@@ -36,6 +36,7 @@
import os.path
import re
import sys
+import platform
import ctypes
import ctypes.util
@@ -136,6 +137,7 @@
dirs.extend(self.other_dirs)
dirs.append(".")
+ dirs.append(os.path.dirname(__file__))
if hasattr(sys, 'frozen') and sys.frozen == 'macosx_app':
dirs.append(os.path.join(
@@ -171,6 +173,7 @@
directories.extend(os.environ[name].split(os.pathsep))
directories.extend(self.other_dirs)
directories.append(".")
+ directories.append(os.path.dirname(__file__))
try:
directories.extend([dir.strip() for dir in open('/etc/ld.so.conf')])
@@ -177,7 +180,21 @@
except IOError:
pass
- directories.extend(['/lib', '/usr/lib', '/lib64', '/usr/lib64'])
+ unix_lib_dirs_list = ['/lib', '/usr/lib', '/lib64', '/usr/lib64']
+ if sys.platform.startswith('linux'):
+ # Try and support multiarch work in Ubuntu
+ # https://wiki.ubuntu.com/MultiarchSpec
+ bitage = platform.architecture()[0]
+ if bitage.startswith('32'):
+ # Assume Intel/AMD x86 compat
+ unix_lib_dirs_list += ['/lib/i386-linux-gnu', '/usr/lib/i386-linux-gnu']
+ elif bitage.startswith('64'):
+ # Assume Intel/AMD x86 compat
+ unix_lib_dirs_list += ['/lib/x86_64-linux-gnu', '/usr/lib/x86_64-linux-gnu']
+ else:
+ # guess...
+ unix_lib_dirs_list += glob.glob('/lib/*linux-gnu')
+ directories.extend(unix_lib_dirs_list)
cache = {}
lib_re = re.compile(r'lib(.*)\.s[ol]')
@@ -236,6 +253,28 @@
class WindowsLibraryLoader(LibraryLoader):
name_formats = ["%s.dll", "lib%s.dll"]
+ def load_library(self, libname):
+ try:
+ result = LibraryLoader.load_library(self, libname)
+ except ImportError:
+ result = None
+ if os.path.sep not in libname:
+ for name in self.name_formats:
+ try:
+ result = getattr(ctypes.cdll, name % libname)
+ if result:
+ break
+ except WindowsError:
+ result = None
+ if result is None:
+ try:
+ result = getattr(ctypes.cdll, libname)
+ except WindowsError:
+ result = None
+ if result is None:
+ raise ImportError("%s not found." % libname)
+ return result
+
def load(self, path):
return _WindowsLibrary(path)
@@ -242,6 +281,9 @@
def getplatformpaths(self, libname):
if os.path.sep not in libname:
for name in self.name_formats:
+ dll_in_current_dir = os.path.abspath(name % libname)
+ if os.path.exists(dll_in_current_dir):
+ yield dll_in_current_dir
path = ctypes.util.find_library(name % libname)
if path:
yield path
@@ -261,7 +303,16 @@
def add_library_search_dirs(other_dirs):
- loader.other_dirs = other_dirs
+ """
+ Add libraries to search paths.
+ If library paths are relative, convert them to absolute with respect to this
+ file's directory
+ """
+ THIS_DIR = os.path.dirname(__file__)
+ for F in other_dirs:
+ if not os.path.isabs(F):
+ F = os.path.abspath(os.path.join(THIS_DIR, F))
+ loader.other_dirs.append(F)
load_library = loader.load_library
Index: lib/python/ctypes/ctypesgencore/messages.py
===================================================================
--- lib/python/ctypes/ctypesgencore/messages.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/messages.py (working copy)
@@ -22,10 +22,20 @@
from __future__ import print_function
import sys
+import logging
__all__ = ["error_message", "warning_message", "status_message"]
+log = logging.getLogger('ctypesgen')
+ch = logging.StreamHandler() # use stdio
+logging_fmt_str = "%(levelname)s: %(message)s"
+formatter = logging.Formatter(logging_fmt_str)
+ch.setFormatter(formatter)
+log.addHandler(ch)
+# default level that ctypesgen was using with original version
+log.setLevel(logging.INFO)
+
def error_message(msg, cls=None):
print("Error: %s" % msg)
Index: lib/python/ctypes/ctypesgencore/options.py
===================================================================
--- lib/python/ctypes/ctypesgencore/options.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/options.py (working copy)
@@ -32,7 +32,11 @@
"other_known_names": [],
"include_macros": True,
"libraries": [],
- "strip_build_path": None
+ "strip_build_path": None,
+ "output_language": "python",
+ "no_stddef_types": False,
+ "no_gnu_types": False,
+ "no_python_types": False,
}
Index: lib/python/ctypes/ctypesgencore/parser/cdeclarations.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/cdeclarations.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/cdeclarations.py (working copy)
@@ -130,8 +130,9 @@
class StructTypeSpecifier(object):
- def __init__(self, is_union, tag, declarations):
+ def __init__(self, is_union, is_packed, tag, declarations):
self.is_union = is_union
+ self.is_packed = is_packed
self.tag = tag
self.declarations = declarations
@@ -140,6 +141,8 @@
s = 'union'
else:
s = 'struct'
+ if self.is_packed:
+ s += ' __attribute__((packed))'
if self.tag:
s += ' %s' % self.tag
if self.declarations:
Index: lib/python/ctypes/ctypesgencore/parser/cgrammar.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/cgrammar.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/cgrammar.py (working copy)
@@ -20,6 +20,10 @@
import warnings
from . import cdeclarations
+try:
+ from . import ctypesparser
+except:
+ import ctypesparser
import ctypesgencore.expressions as expressions
from . import preprocessor
from . import yacc
@@ -40,20 +44,22 @@
'AND_ASSIGN', 'XOR_ASSIGN', 'OR_ASSIGN', 'PERIOD', 'TYPE_NAME',
'TYPEDEF', 'EXTERN', 'STATIC', 'AUTO', 'REGISTER',
- 'CHAR', 'SHORT', 'INT', 'LONG', 'SIGNED', 'UNSIGNED', 'FLOAT', 'DOUBLE',
+ '_BOOL', 'CHAR', 'SHORT', 'INT', 'LONG', 'SIGNED', 'UNSIGNED', 'FLOAT', 'DOUBLE',
'CONST', 'VOLATILE', 'VOID',
'STRUCT', 'UNION', 'ENUM', 'ELLIPSIS',
'CASE', 'DEFAULT', 'IF', 'ELSE', 'SWITCH', 'WHILE', 'DO', 'FOR', 'GOTO',
- 'CONTINUE', 'BREAK', 'RETURN', '__ASM__'
+ 'CONTINUE', 'BREAK', 'RETURN', '__ASM__', '__ATTRIBUTE__', 'PACKED',
+ 'ALIGNED', 'TRANSPARENT_UNION',
)
keywords = [
- 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
+ 'auto', '_Bool', 'break', 'case', 'char', 'const', 'continue', 'default', 'do',
'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int',
'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static',
'struct', 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile',
- 'while', '__asm__'
+ 'while', '__asm__', '__attribute__', 'packed', 'aligned',
+ 'transparent_union',
]
@@ -618,6 +624,7 @@
def p_type_specifier(p):
'''type_specifier : VOID
+ | _BOOL
| CHAR
| SHORT
| INT
@@ -637,8 +644,19 @@
p[0] = cdeclarations.TypeSpecifier(p[1])
+class Attribs(dict):
+ def __init__(self, packed=False, aligned=False, transparent_union=False):
+ super(Attribs, self).__init__(
+ packed=packed, aligned=aligned, transparent_union=transparent_union,
+ )
+ self.__dict__ = self
+
+
def p_struct_or_union_specifier(p):
- '''struct_or_union_specifier : struct_or_union IDENTIFIER '{' struct_declaration_list '}'
+ '''struct_or_union_specifier : struct_or_union gcc_attribs IDENTIFIER '{' struct_declaration_list '}'
+ | struct_or_union gcc_attribs TYPE_NAME '{' struct_declaration_list '}'
+ | struct_or_union gcc_attribs '{' struct_declaration_list '}'
+ | struct_or_union IDENTIFIER '{' struct_declaration_list '}'
| struct_or_union TYPE_NAME '{' struct_declaration_list '}'
| struct_or_union '{' struct_declaration_list '}'
| struct_or_union IDENTIFIER
@@ -647,13 +665,25 @@
# The TYPE_NAME ones are dodgy, needed for Apple headers
# CoreServices.framework/Frameworks/CarbonCore.framework/Headers/Files.h.
# CoreServices.framework/Frameworks/OSServices.framework/Headers/Power.h
- if len(p) == 3:
- p[0] = cdeclarations.StructTypeSpecifier(p[1], p[2], None)
- elif p[2] == '{':
- p[0] = cdeclarations.StructTypeSpecifier(p[1], '', p[3])
+ packed = False
+ if len(p) == 3: # struct <id/typname>
+ p[0] = cdeclarations.StructTypeSpecifier(p[1], False, p[2], None)
else:
- p[0] = cdeclarations.StructTypeSpecifier(p[1], p[2], p[4])
+ if type(p[2]) is Attribs:
+ attribs = p[2]
+ if p[3] == '{':
+ tag, decl = '', p[4]
+ else:
+ tag, decl = p[3], p[5]
+ else:
+ attribs = Attribs()
+ if p[2] == '{':
+ tag, decl = '', p[3]
+ else:
+ tag, decl = p[2], p[4]
+ p[0] = cdeclarations.StructTypeSpecifier(p[1], attribs.packed, tag, decl)
+
p[0].filename = p.slice[0].filename
p[0].lineno = p.slice[0].lineno
@@ -665,6 +695,21 @@
p[0] = p[1] == 'union'
+def p_gcc_attribs(p):
+ '''gcc_attribs : __ATTRIBUTE__ '(' '(' struct_attribute ')' ')'
+ '''
+ p[0] = Attribs()
+ p[0].packed = False if len(p) == 1 else p[4] == 'packed'
+
+
+def p_struct_attribute(p):
+ '''struct_attribute : PACKED
+ | TRANSPARENT_UNION
+ | ALIGNED
+ '''
+ p[0] = p[1]
+
+
def p_struct_declaration_list(p):
'''struct_declaration_list : struct_declaration
| struct_declaration_list struct_declaration
@@ -688,6 +733,11 @@
cdeclarations.apply_specifiers(p[1], declaration)
declaration.declarator = declarator
r += (declaration,)
+ else:
+ # anonymous field (C11/GCC extension)
+ declaration = cdeclarations.Declaration()
+ cdeclarations.apply_specifiers(p[1], declaration)
+ r = (declaration,)
p[0] = r
@@ -909,7 +959,6 @@
'''type_name : specifier_qualifier_list
| specifier_qualifier_list abstract_declarator
'''
- from . import ctypesparser
typ = p[1]
if len(p) == 3:
declarator = p[2]
@@ -919,8 +968,8 @@
declaration = cdeclarations.Declaration()
declaration.declarator = declarator
cdeclarations.apply_specifiers(typ, declaration)
- ctype = ctypesparser.get_ctypes_type(declaration.type,
- declaration.declarator)
+ ctype = p.parser.cparser.get_ctypes_type(declaration.type,
+ declaration.declarator)
p[0] = ctype
Index: lib/python/ctypes/ctypesgencore/parser/cparser.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/cparser.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/cparser.py (working copy)
@@ -63,7 +63,9 @@
t.type = t.value.upper()
elif t.type == 'IDENTIFIER' and t.value in self.type_names:
if (self.pos < 2 or self.tokens[self.pos - 2].type not in
- ('ENUM', 'STRUCT', 'UNION')):
+ ('VOID', '_BOOL', 'CHAR', 'SHORT', 'INT', 'LONG',
+ 'FLOAT', 'DOUBLE', 'SIGNED', 'UNSIGNED', 'ENUM',
+ 'STRUCT', 'UNION', 'TYPE_NAME')):
t.type = 'TYPE_NAME'
t.lexer = self
@@ -101,13 +103,13 @@
self.parser.cparser = self
self.lexer = CLexer(self)
- if stddef_types:
+ if not options.no_stddef_types:
self.lexer.type_names.add('wchar_t')
self.lexer.type_names.add('ptrdiff_t')
self.lexer.type_names.add('size_t')
- if gnu_types:
+ if not options.no_gnu_types:
self.lexer.type_names.add('__builtin_va_list')
- if sys.platform == 'win32':
+ if sys.platform == 'win32' and not options.no_python_types:
self.lexer.type_names.add('__int64')
def parse(self, filename, debug=False):
@@ -212,5 +214,17 @@
def handle_declaration(self, declaration, filename, lineno):
print(declaration)
+ def get_ctypes_type(self, typ, declarator):
+ return typ
+
+ def handle_define_unparseable(self, name, params, value, filename, lineno):
+ if params:
+ original_string = "#define %s(%s) %s" % \
+ (name, ",".join(params), " ".join(value))
+ else:
+ original_string = "#define %s %s" % \
+ (name, " ".join(value))
+ print(original_string)
+
if __name__ == '__main__':
DebugCParser().parse(sys.argv[1], debug=True)
Index: lib/python/ctypes/ctypesgencore/parser/ctypesparser.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/ctypesparser.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/ctypesparser.py (working copy)
@@ -18,154 +18,177 @@
from ctypesgencore.expressions import *
-def get_ctypes_type(typ, declarator, check_qualifiers=False):
- signed = True
- typename = 'int'
- longs = 0
- t = None
+def make_enum_from_specifier(specifier):
+ tag = specifier.tag
- for specifier in typ.specifiers:
- if isinstance(specifier, StructTypeSpecifier):
- t = make_struct_from_specifier(specifier)
- elif isinstance(specifier, EnumSpecifier):
- t = make_enum_from_specifier(specifier)
- elif specifier == 'signed':
- signed = True
- elif specifier == 'unsigned':
- signed = False
- elif specifier == 'long':
- longs += 1
+ enumerators = []
+ last_name = None
+ for e in specifier.enumerators:
+ if e.expression:
+ value = e.expression
else:
- typename = str(specifier)
+ if last_name:
+ value = BinaryExpressionNode("addition", (lambda x, y: x + y),
+ "(%s + %s)", (False, False),
+ IdentifierExpressionNode(
+ last_name),
+ ConstantExpressionNode(1))
+ else:
+ value = ConstantExpressionNode(0)
- if not t:
- # It is a numeric type of some sort
- if (typename, signed, longs) in ctypes_type_map:
- t = CtypesSimple(typename, signed, longs)
+ enumerators.append((e.name, value))
+ last_name = e.name
- elif signed and not longs:
- t = CtypesTypedef(typename)
+ return CtypesEnum(tag, enumerators,
+ src=(specifier.filename, specifier.lineno))
- else:
- name = " ".join(typ.specifiers)
- if typename in [x[0] for x in ctypes_type_map.keys()]:
- # It's an unsupported variant of a builtin type
- error = "Ctypes does not support the type \"%s\"." % name
- else:
- error = "Ctypes does not support adding additional " \
- "specifiers to typedefs, such as \"%s\"" % name
- t = CtypesTypedef(name)
- t.error(error, cls='unsupported-type')
- if declarator and declarator.bitfield:
- t = CtypesBitfield(t, declarator.bitfield)
+def get_decl_id(decl):
+ """Return the identifier of a given declarator"""
+ while isinstance(decl, Pointer):
+ decl = decl.pointer
+ p_name = ""
+ if decl is not None and decl.identifier is not None:
+ p_name = decl.identifier
+ return p_name
- qualifiers = []
- qualifiers.extend(typ.qualifiers)
- while declarator and declarator.pointer:
- if declarator.parameters is not None:
- variadic = "..." in declarator.parameters
- params = []
- for param in declarator.parameters:
- if param == "...":
- break
- params.append(get_ctypes_type(param.type, param.declarator))
- t = CtypesFunction(t, params, variadic)
+class CtypesParser(CParser):
+ '''Parse a C file for declarations that can be used by ctypes.
- a = declarator.array
- while a:
- t = CtypesArray(t, a.size)
- a = a.array
+ Subclass and override the handle_ctypes_* methods.
+ '''
- qualifiers.extend(declarator.qualifiers)
+ def __init__(self, options):
+ super(CtypesParser, self).__init__(options)
+ self.type_map = ctypes_type_map
+ if not options.no_python_types:
+ self.type_map.update(ctypes_type_map_python_builtin)
- t = CtypesPointer(t, declarator.qualifiers)
+ def make_struct_from_specifier(self, specifier):
+ variety = {True: "union", False: "struct"}[specifier.is_union]
+ tag = specifier.tag
- declarator = declarator.pointer
+ if specifier.declarations:
+ members = []
+ for declaration in specifier.declarations:
+ t = self.get_ctypes_type(declaration.type,
+ declaration.declarator,
+ check_qualifiers=True)
+ declarator = declaration.declarator
+ if declarator is None:
+ # Anonymous field in nested union/struct (C11/GCC).
+ name = None
+ else:
+ while declarator.pointer:
+ declarator = declarator.pointer
+ name = declarator.identifier
+ members.append((name, remove_function_pointer(t)))
+ else:
+ members = None
- if declarator and declarator.parameters is not None:
- variadic = "..." in declarator.parameters
+ return CtypesStruct(tag, specifier.is_packed, variety, members,
+ src=(specifier.filename, specifier.lineno))
- params = []
- for param in declarator.parameters:
- if param == "...":
- break
- params.append(get_ctypes_type(param.type, param.declarator))
- t = CtypesFunction(t, params, variadic)
+ def get_ctypes_type(self, typ, declarator, check_qualifiers=False):
+ signed = True
+ typename = 'int'
+ longs = 0
+ t = None
- if declarator:
- a = declarator.array
- while a:
- t = CtypesArray(t, a.size)
- a = a.array
+ for specifier in typ.specifiers:
+ if isinstance(specifier, StructTypeSpecifier):
+ t = self.make_struct_from_specifier(specifier)
+ elif isinstance(specifier, EnumSpecifier):
+ t = make_enum_from_specifier(specifier)
+ elif specifier == 'signed':
+ signed = True
+ elif specifier == 'unsigned':
+ signed = False
+ elif specifier == 'long':
+ longs += 1
+ else:
+ typename = str(specifier)
- if isinstance(t, CtypesPointer) and \
- isinstance(t.destination, CtypesSimple) and \
- t.destination.name == "char" and \
- t.destination.signed:
- t = CtypesSpecial("String")
+ if not t:
+ # It is a numeric type of some sort
+ if (typename, signed, longs) in self.type_map:
+ t = CtypesSimple(typename, signed, longs)
- return t
+ elif signed and not longs:
+ t = CtypesTypedef(typename)
+ else:
+ name = " ".join(typ.specifiers)
+ if typename in [x[0] for x in self.type_map.keys()]:
+ # It's an unsupported variant of a builtin type
+ error = "Ctypes does not support the type \"%s\"." % name
+ else:
+ error = "Ctypes does not support adding additional " \
+ "specifiers to typedefs, such as \"%s\"" % name
+ t = CtypesTypedef(name)
+ t.error(error, cls='unsupported-type')
-def make_struct_from_specifier(specifier):
- variety = {True: "union", False: "struct"}[specifier.is_union]
- tag = specifier.tag
+ if declarator and declarator.bitfield:
+ t = CtypesBitfield(t, declarator.bitfield)
- if specifier.declarations:
- members = []
- for declaration in specifier.declarations:
- t = get_ctypes_type(declaration.type,
- declaration.declarator,
- check_qualifiers=True)
- declarator = declaration.declarator
- if declarator is None:
- # XXX TEMPORARY while struct with no typedef not filled in
- break
- while declarator.pointer:
- declarator = declarator.pointer
- name = declarator.identifier
- members.append((name, remove_function_pointer(t)))
- else:
- members = None
+ qualifiers = []
+ qualifiers.extend(typ.qualifiers)
+ while declarator and declarator.pointer:
+ if declarator.parameters is not None:
+ variadic = "..." in declarator.parameters
- return CtypesStruct(tag, variety, members,
- src=(specifier.filename, specifier.lineno))
+ params = []
+ for param in declarator.parameters:
+ if param == "...":
+ break
+ param_name = get_decl_id(param.declarator)
+ ct = self.get_ctypes_type(param.type, param.declarator)
+ ct.identifier = param_name
+ params.append(ct)
+ t = CtypesFunction(t, params, variadic)
+ a = declarator.array
+ while a:
+ t = CtypesArray(t, a.size)
+ a = a.array
-def make_enum_from_specifier(specifier):
- tag = specifier.tag
+ qualifiers.extend(declarator.qualifiers)
- enumerators = []
- last_name = None
- for e in specifier.enumerators:
- if e.expression:
- value = e.expression
- else:
- if last_name:
- value = BinaryExpressionNode("addition", (lambda x, y: x + y),
- "(%s + %s)", (False, False),
- IdentifierExpressionNode(last_name),
- ConstantExpressionNode(1))
- else:
- value = ConstantExpressionNode(0)
+ t = CtypesPointer(t, tuple(typ.qualifiers) +
+ tuple(declarator.qualifiers))
- enumerators.append((e.name, value))
- last_name = e.name
+ declarator = declarator.pointer
- return CtypesEnum(tag, enumerators,
- src=(specifier.filename, specifier.lineno))
+ if declarator and declarator.parameters is not None:
+ variadic = "..." in declarator.parameters
+ params = []
+ for param in declarator.parameters:
+ if param == "...":
+ break
+ param_name = get_decl_id(param.declarator)
+ ct = self.get_ctypes_type(param.type, param.declarator)
+ ct.identifier = param_name
+ params.append(ct)
+ t = CtypesFunction(t, params, variadic)
-class CtypesParser(CParser):
- '''Parse a C file for declarations that can be used by ctypes.
+ if declarator:
+ a = declarator.array
+ while a:
+ t = CtypesArray(t, a.size)
+ a = a.array
- Subclass and override the handle_ctypes_* methods.
- '''
+ if (isinstance(t, CtypesPointer) and
+ isinstance(t.destination, CtypesSimple) and
+ t.destination.name == "char" and
+ t.destination.signed):
+ t = CtypesSpecial("String")
+ return t
+
def handle_declaration(self, declaration, filename, lineno):
- t = get_ctypes_type(declaration.type, declaration.declarator)
+ t = self.get_ctypes_type(declaration.type, declaration.declarator)
if type(t) in (CtypesStruct, CtypesEnum):
self.handle_ctypes_new_type(
@@ -183,7 +206,7 @@
name, remove_function_pointer(t), filename, lineno)
elif isinstance(t, CtypesFunction):
self.handle_ctypes_function(
- name, t.restype, t.argtypes, t.variadic, filename, lineno)
+ name, t.restype, t.argtypes, t.errcheck, t.variadic, filename, lineno)
elif declaration.storage != 'static':
self.handle_ctypes_variable(name, t, filename, lineno)
@@ -195,7 +218,7 @@
def handle_ctypes_typedef(self, name, ctype, filename, lineno):
pass
- def handle_ctypes_function(self, name, restype, argtypes, filename, lineno):
+ def handle_ctypes_function(self, name, restype, argtypes, errcheck, filename, lineno):
pass
def handle_ctypes_variable(self, name, ctype, filename, lineno):
Index: lib/python/ctypes/ctypesgencore/parser/datacollectingparser.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/datacollectingparser.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/datacollectingparser.py (working copy)
@@ -64,7 +64,7 @@
def parse(self):
fd, fname = mkstemp(suffix=".h")
- f = os.fdopen(fd, 'w+b')
+ f = os.fdopen(fd, 'w')
for header in self.options.other_headers:
print('#include <%s>' % header, file=f)
for header in self.headers:
@@ -71,7 +71,7 @@
print('#include "%s"' % os.path.abspath(header), file=f)
f.flush()
f.close()
- ctypesparser.CtypesParser.parse(self, fname, None)
+ ctypesparser.CtypesParser.parse(self, fname, False)
os.remove(fname)
for name, params, expr, (filename, lineno) in self.saved_macros:
@@ -123,8 +123,8 @@
else:
self.handle_struct(ctype, filename, lineno)
- def handle_ctypes_function(self, name, restype, argtypes, variadic,
- filename, lineno):
+ def handle_ctypes_function(self, name, restype, argtypes, errcheck,
+ variadic, filename, lineno):
# Called by CtypesParser
restype.visit(self)
for argtype in argtypes:
@@ -133,6 +133,7 @@
function = FunctionDescription(name,
restype,
argtypes,
+ errcheck,
variadic=variadic,
src=(filename, repr(lineno)))
@@ -169,6 +170,7 @@
if ctypestruct.opaque:
if name not in self.already_seen_opaque_structs:
struct = StructDescription(ctypestruct.tag,
+ ctypestruct.packed,
ctypestruct.variety,
None, # No members
True, # Opaque
@@ -198,6 +200,7 @@
else:
struct = StructDescription(ctypestruct.tag,
+ ctypestruct.packed,
ctypestruct.variety,
ctypestruct.members,
False, # Not opaque
@@ -223,7 +226,7 @@
if ctypeenum.opaque:
if tag not in self.already_seen_opaque_enums:
enum = EnumDescription(ctypeenum.tag,
- ctypeenum.enumerators,
+ None,
ctypeenum,
src=(filename, str(lineno)))
enum.opaque = True
@@ -240,12 +243,13 @@
enum.opaque = False
enum.ctype = ctypeenum
enum.src = ctypeenum.src
+ enum.members = ctypeenum.enumerators
del self.already_seen_opaque_enums[tag]
else:
enum = EnumDescription(ctypeenum.tag,
- None,
+ ctypeenum.enumerators,
src=(filename, str(lineno)),
ctype=ctypeenum)
enum.opaque = False
Index: lib/python/ctypes/ctypesgencore/parser/lex.py
===================================================================
--- lib/python/ctypes/ctypesgencore/parser/lex.py (revision 73073)
+++ lib/python/ctypes/ctypesgencore/parser/lex.py (working copy)
@@ -43,8 +43,9 @@
import sys
import types
import collections
+import functools
+from grass.script.utils import decode
-
if PY3:
_meth_func = "__func__"
_meth_self = "__self__"
@@ -255,7 +256,10 @@
# input() - Push a new string into the lexer
# ------------------------------------------------------------
def input(self, s):