-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpythonic.py
More file actions
4361 lines (3634 loc) · 146 KB
/
rpythonic.py
File metadata and controls
4361 lines (3634 loc) · 146 KB
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/python
# RPythonic | http://code.google.com/p/rpythonic/
# By Brett, bhartsho@yahoo.com
# License: BSD
VERSION = '0.4.8j'
_doc_ = '''
NAME
RPythonic
DESCRIPTION
RPythonic is a frontend for using RPython (the translation toolchain of PyPy), it simplifies: wrapper generation, compiling (standalone or modules), and Android integration. It can also be used as a tool to automatically wrap C/C++ libraries using ctypes.
INSTALLING
PLY (apt-get install python-ply)
PyLLVM (apt-get install python-llvm)
RPYTHON API
import rpythonic
rpy = rpythonic.RPython( 'name_of_module' )
@rpy.bind(a=float, b=float)
def sub( a, b ): return a-b
rpy.cache()
sub(10,100) # compiled
'''
PYTHON_RESERVED_KEYWORDS = 'for while in as global with try except lambda return raise if else elif eval exec and not or break continue finally print yield del def class assert'.split()
PYTHON_RESERVED_NAMES = 'self id object type enumerate isinstance len globals locals tuple dict list int float str bool getattr setattr hasattr range None True False'.split() + PYTHON_RESERVED_KEYWORDS
import os, sys, ctypes, inspect
import subprocess
ISPYTHON2 = sys.version_info[0] == 2
IS32BIT = (ctypes.sizeof(ctypes.c_void_p)==4)
try:
import CppHeaderParser
print( 'loaded CppHeaderParser' )
import pycparser # including pycparser-2.03
print( 'loaded pycparser' )
except:
print( 'MESSAGE: failed to import pycparser - rpythonic can not generate new wrappers' )
pycparser = None
RPYTHONIC_DIR = os.path.split(os.path.abspath(__file__))[0]
#if RPYTHONIC_DIR not in sys.path: sys.path.append( RPYTHONIC_DIR )
if IS32BIT:
CTYPES_HEADER = '## generated by RPythonic %s | host: 32bits\n' %VERSION
else:
CTYPES_HEADER = '## generated by RPythonic %s | host: 64bits\n' %VERSION
CTYPES_HEADER += '## http://code.google.com/p/rpythonic/'
CTYPES_HEADER += '\n' + open( os.path.join(RPYTHONIC_DIR,'magicheader.py'), 'rb' ).read().decode('utf-8')
#flow space unrolls loops
#wrapped = rlib.unrolling_iterable( somelist )
SEM_NAME = '/rpython_mutex'
PATH2PYPY = os.path.abspath('../pypy')
RAYMOND_HETTINGER = '''
################### Raymond Hettinger's Constant Folding ##################
# Decorator for BindingConstants at compile time
# A recipe by Raymond Hettinger, from Python Cookbook:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940
# updated for Python3 and still compatible with Python2 - by Hart, May17th 2011
try: _BUILTINS_DICT_ = vars(__builtins__)
except: _BUILTINS_DICT_ = __builtins__
ISPYTHON2 = sys.version_info[0] == 2
_HETTINGER_FOLDS_ = 0
def _hettinger_make_constants(f, builtin_only=False, stoplist=[], verbose=0):
from opcode import opmap, HAVE_ARGUMENT, EXTENDED_ARG
global _HETTINGER_FOLDS_
try:
if ISPYTHON2: co = f.func_code; fname = f.func_name
else: co = f.__code__; fname = f.__name__
except AttributeError: return f # Jython doesn't have a func_code attribute.
if ISPYTHON2: newcode = map(ord, co.co_code)
else: newcode = list( co.co_code )
newconsts = list(co.co_consts)
names = co.co_names
codelen = len(newcode)
if ISPYTHON2:
if verbose >= 2: print( f.func_name )
func_globals = f.func_globals
else:
if verbose >= 2: print( f.__name__ )
func_globals = f.__globals__
env = _BUILTINS_DICT_.copy()
if builtin_only:
stoplist = dict.fromkeys(stoplist)
stoplist.update(func_globals)
else:
env.update(func_globals)
# First pass converts global lookups into constants
i = 0
while i < codelen:
opcode = newcode[i]
if opcode in (EXTENDED_ARG, opmap['STORE_GLOBAL']):
if verbose >= 1: print('skipping function', fname)
return f # for simplicity, only optimize common cases
if opcode == opmap['LOAD_GLOBAL']:
oparg = newcode[i+1] + (newcode[i+2] << 8)
name = co.co_names[oparg]
if name in env and name not in stoplist:
value = env[name]
for pos, v in enumerate(newconsts):
if v is value:
break
else:
pos = len(newconsts)
newconsts.append(value)
newcode[i] = opmap['LOAD_CONST']
newcode[i+1] = pos & 0xFF
newcode[i+2] = pos >> 8
_HETTINGER_FOLDS_ += 1
if verbose >= 2:
print( " global constant fold:", name )
i += 1
if opcode >= HAVE_ARGUMENT:
i += 2
# Second pass folds tuples of constants and constant attribute lookups
i = 0
while i < codelen:
newtuple = []
while newcode[i] == opmap['LOAD_CONST']:
oparg = newcode[i+1] + (newcode[i+2] << 8)
newtuple.append(newconsts[oparg])
i += 3
opcode = newcode[i]
if not newtuple:
i += 1
if opcode >= HAVE_ARGUMENT:
i += 2
continue
if opcode == opmap['LOAD_ATTR']:
obj = newtuple[-1]
oparg = newcode[i+1] + (newcode[i+2] << 8)
name = names[oparg]
try:
value = getattr(obj, name)
if verbose >= 2: print( ' folding attribute', name )
except AttributeError:
continue
deletions = 1
elif opcode == opmap['BUILD_TUPLE']:
oparg = newcode[i+1] + (newcode[i+2] << 8)
if oparg != len(newtuple): continue
deletions = len(newtuple)
value = tuple(newtuple)
else: continue
reljump = deletions * 3
newcode[i-reljump] = opmap['JUMP_FORWARD']
newcode[i-reljump+1] = (reljump-3) & 0xFF
newcode[i-reljump+2] = (reljump-3) >> 8
n = len(newconsts)
newconsts.append(value)
newcode[i] = opmap['LOAD_CONST']
newcode[i+1] = n & 0xFF
newcode[i+2] = n >> 8
i += 3
_HETTINGER_FOLDS_ += 1
if verbose >= 2:
print( " folded constant:",value )
if ISPYTHON2:
codestr = ''.join(map(chr, newcode))
codeobj = type(co)(co.co_argcount, co.co_nlocals, co.co_stacksize,
co.co_flags, codestr, tuple(newconsts), co.co_names,
co.co_varnames, co.co_filename, co.co_name,
co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)
return type(f)(codeobj, f.func_globals, f.func_name, f.func_defaults, f.func_closure)
else:
codestr = b''
for s in newcode: codestr += s.to_bytes(1,'little')
codeobj = type(co)(co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize,
co.co_flags, codestr, tuple(newconsts), co.co_names,
co.co_varnames, co.co_filename, co.co_name,
co.co_firstlineno, co.co_lnotab, co.co_freevars,
co.co_cellvars)
return type(f)(codeobj, f.__globals__, f.__name__, f.__defaults__, f.__closure__)
def hettinger_bind_recursive(mc, builtin_only=False, stoplist=[], verbose=0):
"""Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True.
"""
import types
try: d = vars(mc)
except TypeError: return
if ISPYTHON2: recursivetypes = (type, types.ClassType)
else: recursivetypes = (type,)
for k, v in d.items():
if type(v) is types.FunctionType:
newv = _hettinger_make_constants(v, builtin_only, stoplist, verbose)
setattr(mc, k, newv)
elif type(v) in recursivetypes:
hettinger_bind_recursive(v, builtin_only, stoplist, verbose)
def hettinger_transform( module=None ):
global _HETTINGER_FOLDS_
_HETTINGER_FOLDS_ = 0
if not module: module = sys.modules[__name__]
hettinger_bind_recursive( module, verbose=1 )
print( 'HETTINGER: constants folded', _HETTINGER_FOLDS_ )
'''
################### END Raymond Hettinger's Constant Folding ##################
exec( RAYMOND_HETTINGER )
def pprint( txt, color=None ):
if color and sys.platform != "win32": print( '\x1b[%sm'%color + str(txt) + '\x1b[0m' )
else: print( txt )
CACHEDIR = None
def set_cache( path ):
global CACHEDIR
assert os.path.isdir( path )
CACHEDIR = path
if CACHEDIR not in sys.path: sys.path.append( CACHEDIR )
#set_cache( os.path.join( RPYTHONIC_DIR, 'cache' ) )
DEFAULT_CACHEDIR = os.path.join(os.environ['HOME'], '.rpythonic')
if not os.path.isdir( DEFAULT_CACHEDIR ): os.mkdir( DEFAULT_CACHEDIR )
set_cache( DEFAULT_CACHEDIR )
def set_pypy_root( path ):
print('set_pypy_root is DEPRECATED')
assert 0 # DEPRECATED!
global PATH2PYPY
path = os.path.abspath( path )
assert os.path.isdir( path )
PATH2PYPY = path
if path not in sys.path: sys.path.append( PATH2PYPY )
def set_android_sdk_root(path): AndroidPackage.set_sdk_root( path )
def set_android_ndk_root(path): AndroidPackage.set_ndk_root( path )
def _load( name, type, platform='' ):
return __import__(
#'gen%s%s.%s'%(type,platform,name),
name,
fromlist=[name]
)
def load( name, mode='ctypes', platform='', debug=True ): # load module
mod = None
if debug: mod = _load( name, mode, platform )
else:
try: mod = _load( name, mode, platform )
except: print( 'failed to load module', name )
return mod
class ModuleWrapper(object): # TODO DEPRECATE ME
## backdoor to define manual wrappers
# module( somefunc, returns, arg )
def __call__(self, name, result=ctypes.c_void_p, *args ):
_args = args
if args and type(args[0]) not in (tuple,list):
_args = []
for i, arg in enumerate( args ):
_args.append( ('unnamed%s'%i, arg) )
return self.__module._rpythonic_function_( name, result, _args )
def __init__(self, name, module, secondary=None):
self.__name = name
self.__module = module
self.__secondary = secondary
ignorelist = getattr( module, 'RPYTHONIC_AUTOPREFIX_IGNORE' )
count = {}
for n in dir( module ):
if len(n)>=3:
a = ''
for i,char in enumerate( n ):
if i != 0:
if char.isupper(): break # camelCase or CamelCase or prefix_name
elif char == '_': a += '_'; break
a += char
if len(a) < len(n):
if a not in count: count[a] = 0
count[a] += 1
self.__try_names = []
for n in count:
if count[n] > 20 and n not in ignorelist:
print( 'auto prefix', n )
self.__try_names.append( n )
def __getattr__(self, name ):
mod = self.__module
if hasattr( mod, name ): return getattr( mod, name )
elif hasattr( mod, self.__name+name ): return getattr( mod, self.__name+name )
else:
for prefix in self.__try_names:
if hasattr( mod, prefix+name ): return getattr( mod, prefix+name )
if self.__secondary: return getattr( self.__secondary, name )
else: raise AttributeError
def module( name, space=None, mode='ctypes', platform='', secondary=None, fold_constants=False ):
mod = load( name, mode, platform )
if fold_constants: mod.hettinger_transform()
if mod:
if type(space) is dict:
for n in dir(mod):
if not n.startswith('__'): space[ n ] = getattr(mod,n)
return ModuleWrapper( name, mod, secondary )
########### Wrapper API ############
STRIP_PREFIXES = []
CTYPES_FOOTER = ''
def wrap(
name='',
header=None,
library_names=None,
insert_headers=[],
library=None,
dynamic_libs=[],
static_libs=[],
defines=[],
undefines=[],
includes=[],
ctypes=True,
cplusplus=False,
platform='linux',
system_include=None,
ignore_classes = [],
ignore_functions = [],
strip_prefixes = [],
ctypes_footer='' ):
assert name
global LIBS, CTYPES_OUTPUT, RFFI_OUTPUT, INCLUDE_DIRS, SYS_INCLUDE_DIRS, MACRO_DEFS, MACRO_UNDEFS, INSERT_HEADERS, CTYPES_FOOTER, STRIP_PREFIXES
_reset_wrapper_state()
LIBS = []
INCLUDE_DIRS = list(includes) # copy since we modify it
INSERT_HEADERS = list( insert_headers )
SYS_INCLUDE_DIRS = []
CTYPES_FOOTER = ctypes_footer
STRIP_PREFIXES = list( strip_prefixes )
if system_include:
SYS_INCLUDE_DIRS.append( system_include )
INCLUDE_DIRS.append( system_include )
for n in os.listdir( system_include ):
if n=='linux': # for stddef.h
sub = os.path.join( system_include, n )
if sub not in INCLUDE_DIRS: INCLUDE_DIRS.append( sub )
if not library: # DEPRECATE?
libname = '%s.so' %name
if not libname.startswith('lib'): libname = 'lib'+libname
guess1 = os.path.join( '/usr/local/lib', libname )
guess2 = os.path.join( '/usr/lib', libname )
if os.path.isfile( guess1 ): library = guess1
elif os.path.isfile( guess2 ): library = guess2
if library: LIBS.append( library )
MACRO_DEFS = list( defines )
MACRO_UNDEFS = list( undefines )
if '-' in name: # fixes module importing
name = name.replace('-','_')
if ctypes:
mdir = os.path.join( CACHEDIR, name )
if not os.path.isdir( mdir ): os.makedirs( mdir )
## TODO deprecate this global CTYPES_OUTPUT
CTYPES_OUTPUT = os.path.join(name,'__init__.py')
if cplusplus:
a = CPlusPlus( header )
for lib in dynamic_libs: a.add_library( lib )
for lib in static_libs: a.add_library( lib, dynamic=False )
for n in ignore_classes: a.add_ignore_class( n )
for n in ignore_functions: a.add_ignore_function( n )
else: # pycparser C
a = C( header, library_names=library_names )
return a.save( name )
#################################################################
INSERT_HEADERS = [] # for fixing bad headers, or combine multiple headers into one
HEADERS = [] # DEPRECATE TODO
INCLUDE_DIRS = []
MACRO_DEFS = []
MACRO_UNDEFS = []
LIB_NAME = '' # not used?
LIB_PATH = '' # not used?
LIB = '' # ctypes header
FAKE_LIBC = None
LIBS = []
SYS_INCLUDE_DIRS = []
CTYPES_OUTPUT = None
RFFI_OUTPUT = None
CONFIG = {
'include_dirs' : INCLUDE_DIRS,
'link_libs' : LIBS,
'extra_headers' : HEADERS,
}
#from neorpython import *
def isclass( ob, *names ):
cname = ob.__class__.__name__
for name in names:
if cname == name: return True
def _reset_wrapper_state():
SomeThing.Structs.clear()
SomeThing.Unions.clear()
SomeThing.Functions.clear()
SomeThing.Enums.clear()
SomeThing.SomeThings.clear()
SomeThing.Arrays.clear()
SomeThing.Nodes = []
SomeThing.MACRO_GLOBALS.clear()
SomeThing.Types.clear()
SomeThing.Typedefs.clear()
SomeThing.EnumTypes.clear()
class SomeThing(object):
'''
ID, Constant, Typename, Decl, or any subtype of Decl:
TypeDecl
PtrDecl
[ subtypes ]
'''
Structs = {}
Unions = {}
Functions = {}
Enums = {}
SomeThings = {}
Arrays = {}
Nodes = []
MACRO_GLOBALS = {} # TODO, is there a better way to deal with this?
@staticmethod
def sort( things ):
for parent in things:
pidx = things.index( parent )
for child in parent.fields:
type = child.type()
if type.startswith('struct:') or type.startswith('union:'):
if child.cyclic: continue#; print('skipping cyclic', type); # ctypes
name = type.split(':')[-1]
#print('searching', name)
found = False
for cidx,c in enumerate( things ):
if c._name() == name:
found = True
if cidx > pidx:
print('--sort--', name, cidx, pidx)
things.remove( c )
things.insert( pidx, c )
return True
if not found: print('not found', name)
@staticmethod
def get_unions_and_structs(sort=False):
valid = SomeThing.Unions.values() + SomeThing.Structs.values()
r = []
for node in SomeThing.Nodes:
if node in valid: r.append( node )
if not sort: return r
else:
i = 0
while sort and i < 400:
sort = SomeThing.sort( r )
i += 1
print( 'sorts', i )
return r
@staticmethod
def get_enums():
r = []; a = SomeThing.Enums.values(); a.sort()
for e in a:
if e not in r: r.append( e )
return r
@staticmethod
def get_unions(): return SomeThing.Unions.values(); a.sort()
@staticmethod
def get_structs(): return SomeThing.Structs.values(); a.sort()
@staticmethod
def depsort( a ):
sorts = 0
for x in a:
if x.dependson and x.dependson in a:
if a.index( x ) > a.index( x.dependson ):
sorts += 1
a.remove( x )
print( 'depsorting', x )
a.insert( a.index(x.dependson)-1, x )
return sorts
@staticmethod
def get_funcs():
r = []; a = SomeThing.Functions.values(); a.sort()
for e in a:
if e not in r:
if e.name() not in SomeThing.Structs: # may16th 2011
r.append( e )
return r
def get_ancestors(self, ancest=None):
if ancest is None: ancest = []
if self.parent:
ancest.append( self.parent )
return self.parent.get_ancestors( ancest )
else: return ancest
PYTHON_RESERVED_KEYWORDS = PYTHON_RESERVED_KEYWORDS
ReservedNames = PYTHON_RESERVED_NAMES
def name(self): # note: Decl can have a .name but it can be None, decl.type.name should then have the real name
if hasattr(self.ast, 'name' ) and self.ast.name:
if self.ast.name in SomeThing.ReservedNames: return 'C_%s' %self.ast.name
else: return self.ast.name
elif hasattr(self.ast, 'declname') and self.ast.declname:
if self.ast.declname in SomeThing.ReservedNames: return 'C_%s' %self.ast.declname
else: return self.ast.declname
elif self.child: return self.child.name()
def gen_rffi(self, declare=False):
if self.child and self.child.name(): return self.child.gen_rffi( declare )
elif self.tag == 'TypeDecl': return '#%s <TypeDecl=%s>' %(self.name(),self.type())
else: return '#%s <ast=%s>' %(self.name(),self.tag)
def gen_ctypes(self, declare=False):
if self.child and self.child.name(): return self.child.gen_ctypes( declare )
elif self.tag == 'TypeDecl': return '#%s <TypeDecl=%s>' %(self.name(),self.type())
else: return '#%s <ast=%s>' %(self.name(),self.tag)
def gen_python(self):
if self.child and self.child.name(): return self.child.gen_python()
else: return ['#%s <ast=%s>' %(self.name(),self.tag) ]
@classmethod
def get_node_by_name( self, name ):
for n in self.Nodes:
if n.name() == name: return n
Types = {}
Typedefs = {}
EnumTypes = {} # typedef'ed enums are different?
def setup( self ): pass # overloaded
def __init__(self, ast, parent=None ):
SomeThing.Nodes.append( self )
self.cyclic = False # for structs and unions
self.ast = ast
self.tag = ast.__class__.__name__
self.parent = parent
self.array = None # pass the array down the tree
if parent:
## TODO, is this required?
if isclass( parent, 'Array' ): self.array = parent
elif parent.array: self.array = parent.array
elif parent.parent and isclass( parent.parent, 'Array' ):
self.array = parent.parent
elif parent.parent and parent.parent.array:
self.array = parent.parent.array
self.pointer = isclass( ast, 'PtrDecl' )
self.child = None
child = None
if hasattr( ast, 'type' ): child = ast.type
if child:
if isclass( child, 'Struct' ): self.child = Struct( child, parent=self )
elif isclass( child, 'Union' ): self.child = Union( child, parent=self )
elif isclass( child, 'FuncDef', 'FuncDecl' ): self.child = Function( child, parent=self )
elif isclass( child, 'Enum' ): self.child = Enum( child, parent=self )
elif isclass( child, 'ArrayDecl'): #, 'ArrayRef' ):
#child.show()
self.child = Array( child, parent=self )
if self.tag == 'Typedef': self.array = self.child #TODO revisit
elif self.tag == 'Decl': self.array = self.child # structs that contain arrays - may5th
else: self.child = SomeThing( child, parent=self )
if self.tag == 'Typedef':
#print( 'Typedef: %s' %ast.name )
#ast.show()
if ast.name in SomeThing.Typedefs:
#print( SomeThing.Typedefs.keys())
print( '---------- warning duplicate typedef ----------' )
print( ast.name )
ast.show()
#raise SyntaxError
SomeThing.Typedefs[ ast.name ] = self
if self.tag == 'TypeDecl':
if isclass( ast.type, 'IdentifierType' ):
if not ast.type.names: ast.show()
else: SomeThing.Types[ ast.declname ] = ' '.join( ast.type.names ) # fixed may5th
elif isclass( ast.type, 'Struct', 'Union' ):
SomeThing.Types[ ast.declname ] = self.child
elif isclass( ast.type, 'Enum' ):
SomeThing.EnumTypes[ ast.declname ] = self.child
else:
print('TODO - non ident types'); ast.show()
ancest = self.get_ancestors()
self.dependson = None
for p in ancest:
if isclass( p, 'Struct', 'Union' ):
self.dependson = p
break
self.setup()
self.unnamed = False
name = self.name()
if not self.parent and name is None:
self.unnamed = True
if self.child and self.child.tag != 'Enum':
raise
if not name and self.parent: # fixes nested struct problem
name = self.parent.name()
if name:
a = getattr( SomeThing, self.__class__.__name__+'s' )
if name in a:
other = a[name]
if self.ast.__class__.__name__.endswith('Decl'): pass
elif other.ast.__class__.__name__.endswith('Decl'): a[name] = self
else: a[ name ] = self.resolve_conflict( other )
else: a[ name ] = self
def num_ast_nodes( self ): return len(self.flatten_ast_nodes( self.ast ) )
def flatten_ast_nodes( self, ast, nodes=None ):
'''
updated for PyCparser 2.06
'''
if nodes is None: nodes = []
nodes.append( ast )
children = ast.children()
if children: [self.flatten_ast_nodes( child, nodes ) for ext,child in children ]
return nodes
def resolve_conflict( self, other ): # the one with more ast nodes is the one we want rule, never breaks?
if self.num_ast_nodes() > other.num_ast_nodes(): return self
else: return other
def pointers( self, p=None ): # p=[] bad idea
if p is None: p = [] # prevents memleak
if self.pointer: p.append( self )
if self.child: return self.child.pointers( p )
else: return p
def get_child_by_type( self, t ): # june1st 2011
if isinstance( self, t ): return self
elif self.child: return self.child.get_child_by_type( t )
RFFI_TYPEDEF_HACKS = {
'int8_t' : 'SIGNEDCHAR',
'uint8_t' : 'UCHAR',
'int16_t' : 'SHORT',
'uint16_t' : 'USHORT',
'int32_t' : 'INT',
'uint32_t' : 'UINT',
'int64_t' : 'LONG',
'uint64_t' : 'ULONG',
'__builtin_va_list' : 'VOIDP',
}
def rffi_type( self ):
type = self.type()
typedef = self.typedef()
pointers = len(self.pointers())
array = 0
if self.array: array += self.array.length()
if typedef:
pointers += len( typedef.pointers() )
if typedef.array: array += typedef.array.length()
ctype = None
if ':' in type:
if type.startswith('union:') or type.startswith('struct:'):
if not self.name(): ctype = 'rffi.VOIDP' # opaque, un-named union or struct
else: a,ctype = type.split(':')
elif type.startswith('enum:'): ctype = 'rffi.INT'
elif type.startswith('function:'):
if typedef and typedef.name() in SomeThing.Functions:
ctype = SomeThing.Functions[typedef.name()].gen_rffi_funcdef()
else:
#self.ast.show()
fdef = self.get_child_by_type( Function )
#if not fdef and isinstance( self.parent, Function ): fdef = self.parent # some bug, TODO fix me
if fdef: ctype = fdef.gen_rffi_funcdef()
else: ctype = 'rffi.VOIDP'
#else: raise NotImplemented
#else: ctype = 'rffi.VOIDP'
else:
_type = type.split()
if 'unsigned' in _type:
unsigned = 'U'
_type.remove( 'unsigned' )
else: unsigned = ''
if 'signed' in _type:
assert not unsigned
_type.remove( 'signed' )
if _type.count( 'long' ) == 2: ctype = 'rffi.%sLONGLONG' %unsigned
elif 'double' in _type and 'long' in _type: ctype = 'rffi.LONGDOUBLE'
elif 'int' in _type and 'short' in _type: ctype = 'rffi.%sSHORT' %unsigned
elif 'int' in _type and 'long' in _type: ctype = 'rffi.%sLONG' %unsigned
else:
if len(_type) != 1:
self.ast.show()
print( 'WARN: this should never happen', _type )
_type = ['void']
type = _type[0]
if type == 'void': ctype = 'rffi.VOIDP'
elif type == 'size_t': ctype = 'rffi.SIZE_T'
elif type == 'ssize_t': ctype = 'rffi.SSIZE_T'
elif type[-1].isdigit():
if type == 'int8': ctype = 'rffi.SIGNEDCHAR'
elif type == 'uint8': ctype = 'rffi.UCHAR'
elif type == 'int16': ctype = 'rffi.SHORT'
elif type == 'uint16': ctype = 'rffi.USHORT'
elif type == 'int32': ctype = 'rffi.INT'
elif type == 'uint32': ctype = 'rffi.UINT'
elif type == 'int64': ctype = 'rffi.LONG'
elif type == 'uint64': ctype = 'rffi.ULONG'
else:
print( type )
raise NotImplemented
elif type in self.RFFI_TYPEDEF_HACKS:
ctype = 'rffi.%s' %self.RFFI_TYPEDEF_HACKS[ type ]
else:
if type.endswith('_t'):
self.ast.show(); print( type ); assert 0
ctype = 'rffi.%s%s'%(unsigned,type.upper())
if not ctype:
self.ast.show()
if self.type() == '<unknown-type>':
ctype = 'rffi.VOIDP'; print('TODO FIXME')
else:
print( self.type() )
raise NotImplemented
## special case void
if type == 'void' or ctype == 'rffi.VOIDP':
if pointers == 1: ctype = 'rffi.VOIDP'
elif pointers == 2: ctype = 'rffi.VOIDPP'
elif pointers == 3: ctype = 'rffi.CArrayPtr( rffi.VOIDPP )'
elif not pointers: ctype = 'lltype.Void' #lltype.py", line 177, in _inline_is_varsize ->Void> cannot be inlined in structure
else: raise NotImplemented
else:
if array:
ctype = 'rffi.CFixedArray( %s, %s )' %( ctype, array )
#pointers -= 1 # is this correct?
if ':' in type and type.split(':')[0] == 'function':
ctype = 'lltype.Ptr( %s )' %ctype
elif pointers == 1 and not array: # an array is the same as a pointer?
if ':' in type: ctype = 'lltype.Ptr( %s )' %ctype
else:
#ctype = 'lltype.Ptr( %s )' %ctype #TypeError: can only point to a Container type, not to Char
ctype = 'rffi.CArrayPtr( %s )' %ctype
elif pointers > 1:
_a = 'rffi.CArrayPtr(' * pointers
_a += ctype
ctype = _a + ( ')'*pointers )
return ctype
#Usually, ctypes does strict type checking. This means, if you have POINTER(c_int) in the argtypes list of a function or as the type of a member field in a structure definition, only instances of exactly the same type are accepted. There are some exceptions to this rule, where ctypes accepts other objects. For example, you can pass compatible array instances instead of pointer types. So, for POINTER(c_int), ctypes accepts an array of c_int: - from the ctypes tutorial
def ctypes_type( self ): # TODO array for all types
import ctypes
type = self.type()
typedef = self.typedef()
pointers = len(self.pointers())
array = 0
if self.array:
print( 'array item name', self.name() )
length = self.array.length()
if length is None: print('WARN: could not find length of array')
else: array += length
if typedef:
pointers += len( typedef.pointers() )
if typedef.array: array += typedef.array.length()
ctype = None
if ':' in type:
if type.startswith('union:') or type.startswith('struct:'):
if not self.name(): ctype = 'ctypes.c_void_p' # opaque, un-named union or struct
else: a,ctype = type.split(':')
elif type.startswith('enum:'): ctype = 'ctypes.c_int'
elif type.startswith('function:'):
pointers -= 1 # it is funny how ctypes deals with callback functions, or is this only true with typedef'ed functions?
if typedef and typedef.name() in SomeThing.Functions:
ctype = SomeThing.Functions[typedef.name()].gen_ctypes_funcdef()
else: ctype = 'ctypes.c_void_p'
else:
_type = type.split()
if 'unsigned' in _type:
unsigned = 'u'
_type.remove( 'unsigned' )
else: unsigned = ''
if 'signed' in _type:
assert not unsigned
_type.remove( 'signed' )
if _type.count( 'long' ) == 2: ctype = 'ctypes.c_%slonglong' %unsigned
elif 'double' in _type and 'long' in _type:
#ctype = 'ctypes.c_longdouble' # pointer to longdouble is NOT pypy compatible
ctype = 'ctypes.c_double'
elif 'int' in _type and 'short' in _type: ctype = 'ctypes.c_%sint16' %unsigned # correct?
elif 'int' in _type and 'long' in _type: ctype = 'ctypes.c_%sint64' %unsigned # a Long Int on LInux & OSX is 64bits, on Win64 its 32bits
else:
if len(_type) != 1:
self.ast.show()
print( 'WARN: this should never happen', _type )
_type = ['void']
type = _type[0]
if type == 'void': ctype = 'ctypes.c_void_p'
elif type == 'size_t': ctype = 'ctypes.c_size_t'
elif type == 'ssize_t': ctype = 'ctypes.c_ssize_t'
elif type == 'char' and unsigned: ctype = 'ctypes.c_ubyte'
elif hasattr( ctypes, 'c_%s%s'%(unsigned,type) ): # some bug (triggered by webkit) requires "import ctypes" above - check eval's, somehow the "ctypes" global gets deleted!
ctype = 'ctypes.c_%s%s'%(unsigned,type) # should catch most types, even int16
else:
if type == 'uchar': ctype = 'ctypes.c_ubyte'
elif type == '_Bool': ctypes = 'ctypes.c_bool' # special case (found in webkit)
else:
print( 'WARN - bad type:', _type )
raise NotImplemented
if not ctype:
self.ast.show()
if self.type() == '<unknown-type>':
ctype = 'ctypes.c_void_p'; print('TODO FIXME')
elif self.type() == '_Bool': ctype = 'ctypes.c_bool' # special case (found in webkit)
else:
print( self.type() )
raise NotImplemented
if array: # most of the time its an array that may have pointers to it, not an array of pointers.
ctype = '( %s * %s )' %( ctype, array )
if pointers > 0:
_a = 'ctypes.POINTER(' * pointers
_a += ctype
ctype = _a + ( ')'*pointers )
return ctype
def typedef( self ):
if isclass( self.ast, 'IdentifierType' ):
if self.ast.names:
#name = self.ast.names[0] # found bug may4th
name = ' '.join( self.ast.names )
if name in SomeThing.Typedefs: return SomeThing.Typedefs[ name ]
elif self.child: return self.child.typedef()
TYPEDEF_HACKS = {
'int8_t' : 'int8',
'uint8_t' : 'uint8',
'int16_t' : 'int16',
'uint16_t' : 'uint16',
'int32_t' : 'int32',
'uint32_t' : 'uint32',
'int64_t' : 'int64',
'uint64_t' : 'uint64',
}
def type(self):
if isclass( self.ast, 'IdentifierType' ):
if not self.ast.names: return '<unknown-type>'
name = ' '.join(self.ast.names)
#if name in SomeThing.Types: return SomeThing.Types[ name ].type()
if name in SomeThing.Typedefs:
#print( 'lookup typedef', name)
# is this a bug in pycparser? see SDL_JoystickGetAxis - thinks its an int
if name in self.TYPEDEF_HACKS:
return self.TYPEDEF_HACKS[ name ]
else:
typedef = SomeThing.Typedefs[ name ]
#print( typedef )
#typedef.ast.show()
return typedef.type()
elif name in SomeThing.Types: # is this safe, is it even used?
_type = SomeThing.Types[ name ]
if type(_type) is str: return _type
else: return _type.type()
elif name in SomeThing.MACRO_GLOBALS:
#print( 'lookup macro global', name )
type(SomeThing.MACRO_GLOBALS[ name ])
elif name: return name
else:
self.ast.show(); print( self )
raise SyntaxError
elif isclass( self.ast, 'FuncDecl' ): return 'function:%s' %self.name()
elif isclass( self.ast, 'Struct', 'Union' ):
n = self.name()
if not n and self.parent: n = self.parent.name() # nested problem
if isclass( self.ast, 'Struct' ): return 'struct:%s' %n
else: return 'union:%s' %n
elif isclass( self.ast, 'Enum' ): return 'enum:%s' %self.name()
elif self.child: return self.child.type()
else: return '<unknown-type>'
################### end SomeThing ###############
class Array( SomeThing ):
def length( self ):
if self.ast.dim:
val = self.ast.dim
if isclass( val, 'Constant' ): return int(val.value)
elif isclass( val, 'BinaryOp' ):
r = Enum.compute_binaryop( val )
if r is None:
print( 'WARNING, can not find length of array' )
self.ast.show()
return 0
else: return r
elif isclass( val, 'ID' ):
e = Enum.search_for_enum_with_key( val.name )
if e: return e.values_by_key[ val.name ]
elif isclass( val, 'TernaryOp' ):
print('-------------------TODO TernaryOp parser')
self.ast.show()
return 0
else:
print('-------------------big trouble')
print( self.ast.dim, type(self.ast.dim))
self.ast.show()
raise NotImplementedError
else:
# zero length case
return 0
class Enum( SomeThing ): # an enum can be nameless
@staticmethod
def get_enum_value( name ): return SomeThing.Enums[ name ].enum_value( name )
@staticmethod
def search_for_enum_with_key( key ):