forked from albertz/PyCParser
/
interpreter.py
1163 lines (1044 loc) · 40 KB
/
interpreter.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
# PyCParser - interpreter
# by Albert Zeyer, 2011
# code under LGPL
from cparser import *
from cwrapper import CStateWrapper
import _ctypes
import ast
import sys
import inspect
class CWrapValue:
def __init__(self, value, decl=None, **kwattr):
self.value = value
self.decl = decl
for k,v in kwattr.iteritems():
setattr(self, k, v)
def __repr__(self):
s = "<" + self.__class__.__name__ + " "
if self.decl is not None: s += repr(self.decl) + " "
s += repr(self.value)
s += ">"
return s
def getCType(self):
if self.decl is not None: return self.decl.type
elif self.value is not None and hasattr(self.value, "__class__"):
return self.value.__class__
#if isinstance(self.value, (_ctypes._SimpleCData,ctypes.Structure,ctypes.Union)):
return self
def iterIdentifierNames():
S = "abcdefghijklmnopqrstuvwxyz0123456789"
n = 0
while True:
v = []
x = n
while x > 0 or len(v) == 0:
v = [x % len(S)] + v
x /= len(S)
yield "".join(map(lambda x: S[x], v))
n += 1
def iterIdWithPostfixes(name):
if name is None:
for postfix in iterIdentifierNames():
yield "__dummy_" + postfix
return
yield name
for postfix in iterIdentifierNames():
yield name + "_" + postfix
import keyword
PyReservedNames = set(dir(sys.modules["__builtin__"]) + keyword.kwlist + ["ctypes", "helpers"])
def isValidVarName(name):
return name not in PyReservedNames
class GlobalScope:
StateScopeDicts = ["vars", "typedefs", "funcs"]
def __init__(self, interpreter, stateStruct):
self.interpreter = interpreter
self.stateStruct = stateStruct
self.identifiers = {} # name -> CVarDecl | ...
self.names = {} # id(decl) -> name
self.vars = {} # name -> value
def _findId(self, name):
for D in self.StateScopeDicts:
d = getattr(self.stateStruct, D)
o = d.get(name)
if o is not None: return o
return None
def findIdentifier(self, name):
o = self.identifiers.get(name, None)
if o is not None: return o
o = self._findId(name)
if o is None: return None
self.identifiers[name] = o
self.names[id(o)] = name
return o
def findName(self, decl):
name = self.names.get(id(decl), None)
if name is not None: return name
o = self.findIdentifier(decl.name)
if o is None: return None
# Note: `o` might be a different object than `decl`.
# This can happen if `o` is the extern declaration and `decl`
# is the actual variable. Anyway, this is fine.
return o.name
def registerExternVar(self, name_prefix, value=None):
if not isinstance(value, CWrapValue):
value = CWrapValue(value)
for name in iterIdWithPostfixes(name_prefix):
if self.findIdentifier(name) is not None: continue
self.identifiers[name] = value
return name
def registerExterns(self):
self.varname_ctypes = self.registerExternVar("ctypes", ctypes)
self.varname_helpers = self.registerExternVar("helpers", Helpers)
def getVar(self, name):
if name in self.vars: return self.vars[name]
decl = self.findIdentifier(name)
assert isinstance(decl, CVarDecl)
if decl.body is not None:
bodyAst, t = astAndTypeForStatement(self, decl.body)
if isPointerType(decl.type) and not isPointerType(t):
v = decl.body.getConstValue(self.stateStruct)
assert not v, "Global: Initializing pointer type " + str(decl.type) + " only supported with 0 value but we got " + str(v) + " from " + str(decl.body)
valueAst = getAstNode_newTypeInstance(self.interpreter, decl.type)
else:
valueAst = getAstNode_newTypeInstance(self.interpreter, decl.type, bodyAst, t)
else:
valueAst = getAstNode_newTypeInstance(self.interpreter, decl.type)
v = evalValueAst(self, valueAst, "<PyCParser_globalvar_" + name + "_init>")
self.vars[name] = v
return v
def evalValueAst(funcEnv, valueAst, srccode_name=None):
if srccode_name is None: srccode_name = "<PyCParser_dynamic_eval>"
valueExprAst = ast.Expression(valueAst)
ast.fix_missing_locations(valueExprAst)
valueCode = compile(valueExprAst, "<PyCParser_globalvar_" + srccode_name + "_init>", "eval")
v = eval(valueCode, funcEnv.interpreter.globalsDict)
return v
class GlobalsWrapper:
def __init__(self, globalScope):
self.globalScope = globalScope
def __setattr__(self, name, value):
self.__dict__[name] = value
def __getattr__(self, name):
decl = self.globalScope.findIdentifier(name)
if decl is None: raise KeyError
if isinstance(decl, CVarDecl):
v = self.globalScope.getVar(name)
elif isinstance(decl, CWrapValue):
v = decl.value
elif isinstance(decl, CFunc):
v = self.globalScope.interpreter.getFunc(name)
elif isinstance(decl, (CTypedef,CStruct,CUnion,CEnum)):
v = getCType(decl, self.globalScope.stateStruct)
elif isinstance(decl, CFuncPointerDecl):
v = getCType(decl, self.globalScope.stateStruct)
else:
assert False, "didn't expected " + str(decl)
self.__dict__[name] = v
return v
def __repr__(self):
return "<" + self.__class__.__name__ + " " + repr(self.__dict__) + ">"
class GlobalsStructWrapper:
def __init__(self, globalScope):
self.globalScope = globalScope
def __setattr__(self, name, value):
self.__dict__[name] = value
def __getattr__(self, name):
decl = self.globalScope.stateStruct.structs.get(name)
if decl is None: raise AttributeError
v = getCType(decl, self.globalScope.stateStruct)
self.__dict__[name] = v
return v
def __repr__(self):
return "<" + self.__class__.__name__ + " " + repr(self.__dict__) + ">"
class FuncEnv:
def __init__(self, globalScope):
self.globalScope = globalScope
self.interpreter = globalScope.interpreter
self.vars = {} # name -> varDecl
self.varNames = {} # id(varDecl) -> name
self.scopeStack = [] # FuncCodeblockScope
self.astNode = ast.FunctionDef(
args=ast.arguments(args=[], vararg=None, kwarg=None, defaults=[]),
body=[], decorator_list=[])
def __repr__(self):
try: return "<" + self.__class__.__name__ + " of " + self.astNode.name + ">"
except: return "<" + self.__class__.__name__ + " in invalid state>"
def _registerNewVar(self, varName, varDecl):
if varDecl is not None:
assert id(varDecl) not in self.varNames
for name in iterIdWithPostfixes(varName):
if not isValidVarName(name): continue
if self.searchVarName(name) is None:
self.vars[name] = varDecl
if varDecl is not None:
self.varNames[id(varDecl)] = name
return name
def searchVarName(self, varName):
if varName in self.vars: return self.vars[varName]
return self.globalScope.findIdentifier(varName)
def registerNewVar(self, varName, varDecl=None):
return self.scopeStack[-1].registerNewVar(varName, varDecl)
def getAstNodeForVarDecl(self, varDecl):
assert varDecl is not None
if id(varDecl) in self.varNames:
# local var
name = self.varNames[id(varDecl)]
assert name is not None
return ast.Name(id=name, ctx=ast.Load())
# we expect this is a global
name = self.globalScope.findName(varDecl)
assert name is not None, str(varDecl) + " is expected to be a global var"
return getAstNodeAttrib("g", name)
def _unregisterVar(self, varName):
varDecl = self.vars[varName]
if varDecl is not None:
del self.varNames[id(varDecl)]
del self.vars[varName]
def pushScope(self, bodyStmntList):
scope = FuncCodeblockScope(funcEnv=self, body=bodyStmntList)
self.scopeStack += [scope]
return scope
def popScope(self):
scope = self.scopeStack.pop()
scope.finishMe()
def getBody(self):
return self.scopeStack[-1].body
NoneAstNode = ast.Name(id="None", ctx=ast.Load())
def getAstNodeAttrib(value, attrib, ctx=ast.Load()):
a = ast.Attribute(ctx=ctx)
if isinstance(value, (str,unicode)):
a.value = ast.Name(id=str(value), ctx=ctx)
elif isinstance(value, ast.AST):
a.value = value
else:
assert False, str(value) + " has invalid type"
assert attrib is not None
a.attr = str(attrib)
return a
def getAstNodeForCTypesBasicType(t):
if t is None: return NoneAstNode
if t is CVoidType: return NoneAstNode
if not inspect.isclass(t) and isinstance(t, CVoidType): return NoneAstNode
if inspect.isclass(t) and issubclass(t, CVoidType): return None
assert issubclass(t, getattr(ctypes, t.__name__))
return getAstNodeAttrib("ctypes", t.__name__)
def getAstNodeForVarType(interpreter, t):
if isinstance(t, CBuiltinType):
return getAstNodeForCTypesBasicType(State.CBuiltinTypes[t.builtinType])
elif isinstance(t, CStdIntType):
return getAstNodeForCTypesBasicType(State.StdIntTypes[t.name])
elif isinstance(t, CPointerType):
a = getAstNodeAttrib("ctypes", "POINTER")
return makeAstNodeCall(a, getAstNodeForVarType(interpreter, t.pointerOf))
elif isinstance(t, CTypedefType):
return getAstNodeAttrib("g", t.name)
elif isinstance(t, CStruct):
if t.name is None:
# We have a problem. Actually, I wonder how this can happen.
# But we have an anonymous struct here.
# Wrap it via CWrapValue
v = getAstForWrapValue(interpreter, CWrapValue(t))
return getAstNodeAttrib(v, "value")
# TODO: this assumes the was previously declared globally.
return getAstNodeAttrib("structs", t.name)
else:
try: return getAstNodeForCTypesBasicType(t)
except: pass
assert False, "cannot handle " + str(t)
def findHelperFunc(f):
for k in dir(Helpers):
v = getattr(Helpers, k)
if v is f: return k
return None
def makeAstNodeCall(func, *args):
if not isinstance(func, ast.AST):
name = findHelperFunc(func)
assert name is not None, str(func) + " unknown"
func = getAstNodeAttrib("helpers", name)
return ast.Call(func=func, args=list(args), keywords=[], starargs=None, kwargs=None)
def isPointerType(t):
if isinstance(t, CPointerType): return True
if isinstance(t, CFuncPointerDecl): return True
from inspect import isclass
if isclass(t):
if issubclass(t, _ctypes._Pointer): return True
if issubclass(t, ctypes.c_void_p): return True
return False
def isValueType(t):
if isinstance(t, (CBuiltinType,CStdIntType)): return True
from inspect import isclass
if isclass(t):
for c in State.StdIntTypes.values():
if issubclass(t, c): return True
return False
def getAstNode_valueFromObj(stateStruct, objAst, objType):
if isPointerType(objType):
from inspect import isclass
if not isclass(objType) or not issubclass(objType, ctypes.c_void_p):
astVoidPT = getAstNodeAttrib("ctypes", "c_void_p")
astCast = getAstNodeAttrib("ctypes", "cast")
astVoidP = makeAstNodeCall(astCast, objAst, astVoidPT)
else:
astVoidP = objAst
astValue = getAstNodeAttrib(astVoidP, "value")
return ast.BoolOp(op=ast.Or(), values=[astValue, ast.Num(0)])
elif isValueType(objType):
astValue = getAstNodeAttrib(objAst, "value")
return astValue
elif isinstance(objType, CTypedefType):
t = stateStruct.typedefs[objType.name]
return getAstNode_valueFromObj(stateStruct, objAst, t)
else:
assert False, "bad type: " + str(objType)
def getAstNode_newTypeInstance(interpreter, objType, argAst=None, argType=None):
typeAst = getAstNodeForVarType(interpreter, objType)
if isPointerType(objType) and isPointerType(argType):
# We can have it simpler. This is even important in some cases
# were the pointer instance is temporary and the object
# would get freed otherwise!
astCast = getAstNodeAttrib("ctypes", "cast")
return makeAstNodeCall(astCast, argAst, typeAst)
args = []
if argAst is not None:
if isinstance(argAst, (ast.Str, ast.Num)):
args += [argAst]
elif argType is not None:
args += [getAstNode_valueFromObj(interpreter._cStateWrapper, argAst, argType)]
else:
# expect that it is the AST for the value.
# there is no really way to 'assert' this.
args += [argAst]
if isPointerType(objType) and argAst is not None:
assert False, "not supported because unsafe! " + str(argAst)
return makeAstNodeCall(typeAst)
#astVoidPT = getAstNodeAttrib("ctypes", "c_void_p")
#astCast = getAstNodeAttrib("ctypes", "cast")
#astVoidP = makeAstNodeCall(astVoidPT, *args)
#return makeAstNodeCall(astCast, astVoidP, typeAst)
else:
return makeAstNodeCall(typeAst, *args)
class FuncCodeblockScope:
def __init__(self, funcEnv, body):
self.varNames = set()
self.funcEnv = funcEnv
self.body = body
def registerNewVar(self, varName, varDecl):
varName = self.funcEnv._registerNewVar(varName, varDecl)
assert varName is not None
self.varNames.add(varName)
a = ast.Assign()
a.targets = [ast.Name(id=varName, ctx=ast.Store())]
if varDecl is None:
a.value = ast.Name(id="None", ctx=ast.Load())
elif isinstance(varDecl, CFuncArgDecl):
# Note: We just assume that the parameter has the correct/same type.
a.value = getAstNode_newTypeInstance(self.funcEnv.interpreter, varDecl.type, ast.Name(id=varName, ctx=ast.Load()), varDecl.type)
elif isinstance(varDecl, CVarDecl):
if varDecl.body is not None:
bodyAst, t = astAndTypeForStatement(self.funcEnv, varDecl.body)
if isPointerType(varDecl.type) and not isPointerType(t):
v = varDecl.body.getConstValue(self.funcEnv.globalScope.stateStruct)
assert not v, "Initializing pointer type " + str(varDecl.type) + " only supported with 0 value but we got " + str(v) + " from " + str(varDecl.body)
a.value = getAstNode_newTypeInstance(self.funcEnv.interpreter, varDecl.type)
else:
a.value = getAstNode_newTypeInstance(self.funcEnv.interpreter, varDecl.type, bodyAst, t)
else:
a.value = getAstNode_newTypeInstance(self.funcEnv.interpreter, varDecl.type)
elif isinstance(varDecl, CFunc):
# TODO: register func, ...
a.value = ast.Name(id="None", ctx=ast.Load())
else:
assert False, "didn't expected " + str(varDecl)
self.body.append(a)
return varName
def _astForDeleteVar(self, varName):
assert varName is not None
return ast.Delete(targets=[ast.Name(id=varName, ctx=ast.Del())])
def finishMe(self):
astCmds = []
for varName in self.varNames:
astCmds += [self._astForDeleteVar(varName)]
self.funcEnv._unregisterVar(varName)
self.varNames.clear()
self.body.extend(astCmds)
OpUnary = {
"~": ast.Invert,
"!": ast.Not,
"+": ast.UAdd,
"-": ast.USub,
}
OpBin = {
"+": ast.Add,
"-": ast.Sub,
"*": ast.Mult,
"/": ast.Div,
"%": ast.Mod,
"<<": ast.LShift,
">>": ast.RShift,
"|": ast.BitOr,
"^": ast.BitXor,
"&": ast.BitAnd,
}
OpBinBool = {
"&&": ast.And,
"||": ast.Or,
}
OpBinCmp = {
"==": ast.Eq,
"!=": ast.NotEq,
"<": ast.Lt,
"<=": ast.LtE,
">": ast.Gt,
">=": ast.GtE,
}
OpAugAssign = dict(map(lambda (k,v): (k + "=", v), OpBin.iteritems()))
def _astOpToFunc(op):
if inspect.isclass(op): op = op()
assert isinstance(op, ast.operator)
l = ast.Lambda()
a = l.args = ast.arguments()
a.args = [
ast.Name(id="a", ctx=ast.Param()),
ast.Name(id="b", ctx=ast.Param())]
a.vararg = None
a.kwarg = None
a.defaults = []
t = l.body = ast.BinOp()
t.left = ast.Name(id="a", ctx=ast.Load())
t.right = ast.Name(id="b", ctx=ast.Load())
t.op = op
expr = ast.Expression(body=l)
ast.fix_missing_locations(expr)
code = compile(expr, "<_astOpToFunc>", "eval")
f = eval(code)
return f
OpBinFuncs = dict(map(lambda op: (op, _astOpToFunc(op)), OpBin.itervalues()))
class Helpers:
@staticmethod
def prefixInc(a):
a.value += 1
return a
@staticmethod
def prefixDec(a):
a.value -= 1
return a
@staticmethod
def postfixInc(a):
b = Helpers.copy(a)
a.value += 1
return b
@staticmethod
def postfixDec(a):
b = Helpers.copy(a)
a.value -= 1
return b
@staticmethod
def prefixIncPtr(a):
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value += ctypes.sizeof(a._type_)
return a
@staticmethod
def prefixDecPtr(a):
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value -= ctypes.sizeof(a._type_)
return a
@staticmethod
def postfixIncPtr(a):
b = Helpers.copy(a)
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value += ctypes.sizeof(a._type_)
return b
@staticmethod
def postfixDecPtr(a):
b = Helpers.copy(a)
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value -= ctypes.sizeof(a._type_)
return b
@staticmethod
def copy(a):
if isinstance(a, _ctypes._SimpleCData):
c = a.__class__()
ctypes.pointer(c)[0] = a
return c
if isinstance(a, _ctypes._Pointer):
return ctypes.cast(a, a.__class__)
assert False, "cannot copy " + str(a)
@staticmethod
def assign(a, bValue):
a.value = bValue
return a
@staticmethod
def assignPtr(a, bValue):
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value = bValue
return a
@staticmethod
def augAssign(a, op, bValue):
a.value = OpBinFuncs[op](a.value, bValue)
return a
@staticmethod
def augAssignPtr(a, op, bValue):
assert op in ("+","-")
op = OpBin[op]
bValue *= ctypes.sizeof(a._type_)
aPtr = ctypes.cast(ctypes.pointer(a), ctypes.POINTER(ctypes.c_void_p))
aPtr.contents.value = OpBinFuncs[op](aPtr.contents.value, bValue)
return a
@staticmethod
def ptrArithmetic(a, op, bValue):
return Helpers.augAssignPtr(Helpers.copy(a), op, bValue)
def astForHelperFunc(helperFuncName, *astArgs):
helperFuncAst = getAstNodeAttrib("helpers", helperFuncName)
a = ast.Call(keywords=[], starargs=None, kwargs=None)
a.func = helperFuncAst
a.args = list(astArgs)
return a
def getAstNodeArrayIndex(base, index, ctx=ast.Load()):
a = ast.Subscript(ctx=ctx)
if isinstance(base, (str,unicode)):
base = ast.Name(id=base, ctx=ctx)
elif isinstance(base, ast.AST):
pass # ok
else:
assert False, "base " + str(base) + " has invalid type"
if isinstance(index, ast.AST):
pass # ok
elif isinstance(index, (int,long)):
index = ast.Num(index)
else:
assert False, "index " + str(index) + " has invalid type"
a.value = base
a.slice = ast.Index(value=index)
return a
def getAstForWrapValue(interpreter, wrapValue):
interpreter.wrappedValuesDict[id(wrapValue)] = wrapValue
v = getAstNodeArrayIndex("values", id(wrapValue))
return v
def astAndTypeForStatement(funcEnv, stmnt):
if isinstance(stmnt, (CVarDecl,CFuncArgDecl)):
return funcEnv.getAstNodeForVarDecl(stmnt), stmnt.type
elif isinstance(stmnt, CFunc):
# TODO: specify type correctly
return funcEnv.getAstNodeForVarDecl(stmnt), CFuncPointerDecl()
elif isinstance(stmnt, CStatement):
return astAndTypeForCStatement(funcEnv, stmnt)
elif isinstance(stmnt, CAttribAccessRef):
assert stmnt.name is not None
a = ast.Attribute(ctx=ast.Load())
a.value, t = astAndTypeForStatement(funcEnv, stmnt.base)
a.attr = stmnt.name
while isinstance(t, CTypedefType):
t = funcEnv.globalScope.stateStruct.typedefs[t.name]
assert isinstance(t, (CStruct,CUnion))
attrDecl = t.findAttrib(funcEnv.globalScope.stateStruct, a.attr)
assert attrDecl is not None, "attrib " + str(a.attr) + " not found"
return a, attrDecl.type
elif isinstance(stmnt, CPtrAccessRef):
# build equivalent AttribAccess statement
derefStmnt = CStatement()
derefStmnt._op = COp("*")
derefStmnt._rightexpr = stmnt.base
attrStmnt = CAttribAccessRef()
attrStmnt.base = derefStmnt
attrStmnt.name = stmnt.name
return astAndTypeForStatement(funcEnv, attrStmnt)
elif isinstance(stmnt, CNumber):
t = minCIntTypeForNums(stmnt.content, useUnsignedTypes=False)
if t is None: t = "int64_t" # it's an overflow; just take a big type
t = CStdIntType(t)
return getAstNode_newTypeInstance(funcEnv.interpreter, t, ast.Num(n=stmnt.content)), t
elif isinstance(stmnt, CStr):
t = CPointerType(ctypes.c_byte)
v = makeAstNodeCall(getAstNodeAttrib("ctypes", "c_char_p"), ast.Str(s=str(stmnt.content)))
return getAstNode_newTypeInstance(funcEnv.interpreter, t, v, t), t
elif isinstance(stmnt, CChar):
return makeAstNodeCall(getAstNodeAttrib("ctypes", "c_byte"), ast.Num(ord(str(stmnt.content)))), ctypes.c_byte
elif isinstance(stmnt, CFuncCall):
if isinstance(stmnt.base, CFunc):
assert stmnt.base.name is not None
a = ast.Call(keywords=[], starargs=None, kwargs=None)
a.func = getAstNodeAttrib("g", stmnt.base.name)
a.args = map(lambda arg: astAndTypeForStatement(funcEnv, arg)[0], stmnt.args)
return a, stmnt.base.type
elif isinstance(stmnt.base, CSizeofSymbol):
assert len(stmnt.args) == 1
t = getCType(stmnt.args[0], funcEnv.globalScope.stateStruct)
assert t is not None
s = ctypes.sizeof(t)
return ast.Num(s), ctypes.c_size_t
elif isinstance(stmnt.base, CStatement) and stmnt.base.isCType():
# C static cast
assert len(stmnt.args) == 1
bAst, bType = astAndTypeForStatement(funcEnv, stmnt.args[0])
bValueAst = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, bAst, bType)
aType = stmnt.base.asType()
aTypeAst = getAstNodeForVarType(funcEnv.globalScope.interpreter, aType)
if isPointerType(aType):
astVoidPT = getAstNodeAttrib("ctypes", "c_void_p")
astCast = getAstNodeAttrib("ctypes", "cast")
astVoidP = makeAstNodeCall(astVoidPT, bValueAst)
return makeAstNodeCall(astCast, astVoidP, aTypeAst), aType
else:
return makeAstNodeCall(aTypeAst, bValueAst), aType
elif isinstance(stmnt.base, CStatement):
# func ptr call
a = ast.Call(keywords=[], starargs=None, kwargs=None)
pAst, pType = astAndTypeForStatement(funcEnv, stmnt.base)
assert isinstance(pType, CFuncPointerDecl)
a.func = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, pAst, pType)
a.args = map(lambda arg: astAndTypeForStatement(funcEnv, arg)[0], stmnt.args)
return a, pType.type
elif isinstance(stmnt.base, CWrapValue):
# expect that we just wrapped a callable function/object
a = ast.Call(keywords=[], starargs=None, kwargs=None)
a.func = getAstNodeAttrib(getAstForWrapValue(funcEnv.globalScope.interpreter, stmnt.base), "value")
a.args = map(lambda arg: astAndTypeForStatement(funcEnv, arg)[0], stmnt.args)
return a, stmnt.base.returnType
else:
assert False, "cannot handle " + str(stmnt.base) + " call"
elif isinstance(stmnt, CArrayIndexRef):
aAst, aType = astAndTypeForStatement(funcEnv, stmnt.base)
assert isinstance(aType, CPointerType)
assert len(stmnt.args) == 1
# kind of a hack: create equivalent ptr arithmetic expression
ptrStmnt = CStatement()
ptrStmnt._leftexpr = stmnt.base
ptrStmnt._op = COp("+")
ptrStmnt._rightexpr = stmnt.args[0]
derefStmnt = CStatement()
derefStmnt._op = COp("*")
derefStmnt._rightexpr = ptrStmnt
return astAndTypeForCStatement(funcEnv, derefStmnt)
# TODO: support for real arrays.
# the following code may be useful
#bAst, bType = astAndTypeForStatement(funcEnv, stmnt.args[0])
#bValueAst = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, bAst, bType)
#return getAstNodeArrayIndex(aAst, bValueAst), aType.pointerOf
elif isinstance(stmnt, CWrapValue):
v = getAstForWrapValue(funcEnv.globalScope.interpreter, stmnt)
return getAstNodeAttrib(v, "value"), stmnt.getCType()
else:
assert False, "cannot handle " + str(stmnt)
def getAstNode_assign(stateStruct, aAst, aType, bAst, bType):
bValueAst = getAstNode_valueFromObj(stateStruct, bAst, bType)
if isPointerType(aType):
return makeAstNodeCall(Helpers.assignPtr, aAst, bValueAst)
return makeAstNodeCall(Helpers.assign, aAst, bValueAst)
def getAstNode_augAssign(stateStruct, aAst, aType, opStr, bAst, bType):
opAst = ast.Str(opStr)
bValueAst = getAstNode_valueFromObj(stateStruct, bAst, bType)
if isPointerType(aType):
return makeAstNodeCall(Helpers.augAssignPtr, aAst, opAst, bValueAst)
return makeAstNodeCall(Helpers.augAssign, aAst, opAst, bValueAst)
def getAstNode_prefixInc(aAst, aType):
if isPointerType(aType):
return makeAstNodeCall(Helpers.prefixIncPtr, aAst)
return makeAstNodeCall(Helpers.prefixInc, aAst)
def getAstNode_prefixDec(aAst, aType):
if isPointerType(aType):
return makeAstNodeCall(Helpers.prefixDecPtr, aAst)
return makeAstNodeCall(Helpers.prefixDec, aAst)
def getAstNode_postfixInc(aAst, aType):
if isPointerType(aType):
return makeAstNodeCall(Helpers.postfixIncPtr, aAst)
return makeAstNodeCall(Helpers.postfixInc, aAst)
def getAstNode_postfixDec(aAst, aType):
if isPointerType(aType):
return makeAstNodeCall(Helpers.postfixDecPtr, aAst)
return makeAstNodeCall(Helpers.postfixDec, aAst)
def getAstNode_ptrBinOpExpr(stateStruct, aAst, aType, opStr, bAst, bType):
assert isPointerType(aType)
opAst = ast.Str(opStr)
bValueAst = getAstNode_valueFromObj(stateStruct, bAst, bType)
return makeAstNodeCall(Helpers.ptrArithmetic, aAst, opAst, bValueAst)
def astAndTypeForCStatement(funcEnv, stmnt):
assert isinstance(stmnt, CStatement)
if stmnt._leftexpr is None: # prefixed only
rightAstNode,rightType = astAndTypeForStatement(funcEnv, stmnt._rightexpr)
if stmnt._op.content == "++":
return getAstNode_prefixInc(rightAstNode, rightType), rightType
elif stmnt._op.content == "--":
return getAstNode_prefixDec(rightAstNode, rightType), rightType
elif stmnt._op.content == "*":
while isinstance(rightType, CTypedefType):
rightType = funcEnv.globalScope.stateStruct.typedefs[rightType.name]
if isinstance(rightType, CPointerType):
return getAstNodeAttrib(rightAstNode, "contents"), rightType.pointerOf
elif isinstance(rightType, CFuncPointerDecl):
return rightAstNode, rightType # we cannot really dereference a funcptr with ctypes ...
else:
assert False, str(stmnt) + " has bad type " + str(rightType)
elif stmnt._op.content == "&":
return makeAstNodeCall(getAstNodeAttrib("ctypes", "pointer"), rightAstNode), CPointerType(rightType)
elif stmnt._op.content in OpUnary:
a = ast.UnaryOp()
a.op = OpUnary[stmnt._op.content]()
if isPointerType(rightType):
assert stmnt._op.content == "!", "the only supported unary op for ptr types is '!'"
a.operand = makeAstNodeCall(
ast.Name(id="bool", ctx=ast.Load()),
rightAstNode)
rightType = ctypes.c_int
else:
a.operand = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, rightAstNode, rightType)
return getAstNode_newTypeInstance(funcEnv.interpreter, rightType, a), rightType
else:
assert False, "unary prefix op " + str(stmnt._op) + " is unknown"
if stmnt._op is None:
return astAndTypeForStatement(funcEnv, stmnt._leftexpr)
if stmnt._rightexpr is None:
leftAstNode, leftType = astAndTypeForStatement(funcEnv, stmnt._leftexpr)
if stmnt._op.content == "++":
return getAstNode_postfixInc(leftAstNode, leftType), leftType
elif stmnt._op.content == "--":
return getAstNode_postfixDec(leftAstNode, leftType), leftType
else:
assert False, "unary postfix op " + str(stmnt._op) + " is unknown"
leftAstNode, leftType = astAndTypeForStatement(funcEnv, stmnt._leftexpr)
rightAstNode, rightType = astAndTypeForStatement(funcEnv, stmnt._rightexpr)
if stmnt._op.content == "=":
return getAstNode_assign(funcEnv.globalScope.stateStruct, leftAstNode, leftType, rightAstNode, rightType), leftType
elif stmnt._op.content in OpAugAssign:
return getAstNode_augAssign(funcEnv.globalScope.stateStruct, leftAstNode, leftType, stmnt._op.content, rightAstNode, rightType), leftType
elif stmnt._op.content in OpBinBool:
a = ast.BoolOp()
a.op = OpBinBool[stmnt._op.content]()
a.values = [
getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, leftAstNode, leftType),
getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, rightAstNode, rightType)]
return getAstNode_newTypeInstance(funcEnv.interpreter, ctypes.c_int, a), ctypes.c_int
elif stmnt._op.content in OpBinCmp:
a = ast.Compare()
a.ops = [OpBinCmp[stmnt._op.content]()]
a.left = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, leftAstNode, leftType)
a.comparators = [getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, rightAstNode, rightType)]
return getAstNode_newTypeInstance(funcEnv.interpreter, ctypes.c_int, a), ctypes.c_int
elif stmnt._op.content == "?:":
middleAstNode, middleType = astAndTypeForStatement(funcEnv, stmnt._middleexpr)
a = ast.IfExp()
a.test = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, leftAstNode, leftType)
a.body = middleAstNode
a.orelse = rightAstNode
# TODO: we take the type from middleType right now. not really correct...
# So, cast the orelse part.
a.orelse = getAstNode_newTypeInstance(funcEnv.interpreter, middleType, a.orelse, rightType)
return a, middleType
elif isPointerType(leftType):
return getAstNode_ptrBinOpExpr(
funcEnv.globalScope.stateStruct,
leftAstNode, leftType,
stmnt._op.content,
rightAstNode, rightType), leftType
elif stmnt._op.content in OpBin:
a = ast.BinOp()
a.op = OpBin[stmnt._op.content]()
a.left = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, leftAstNode, leftType)
a.right = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, rightAstNode, rightType)
return getAstNode_newTypeInstance(funcEnv.interpreter, leftType, a), leftType # TODO: not really correct. e.g. int + float -> float
else:
assert False, "binary op " + str(stmnt._op) + " is unknown"
PyAstNoOp = ast.Assert(test=ast.Name(id="True", ctx=ast.Load()), msg=None)
def astForCWhile(funcEnv, stmnt):
assert isinstance(stmnt, CWhileStatement)
assert len(stmnt.args) == 1
assert isinstance(stmnt.args[0], CStatement)
whileAst = ast.While(body=[], orelse=[])
whileAst.test = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, *astAndTypeForCStatement(funcEnv, stmnt.args[0]))
funcEnv.pushScope(whileAst.body)
if stmnt.body is not None:
cCodeToPyAstList(funcEnv, stmnt.body)
if not whileAst.body: whileAst.body.append(ast.Pass())
funcEnv.popScope()
return whileAst
def astForCFor(funcEnv, stmnt):
assert isinstance(stmnt, CForStatement)
assert len(stmnt.args) == 3
assert isinstance(stmnt.args[1], CStatement) # second arg is the check; we must be able to evaluate that
# introduce dummy 'if' AST so that we have a scope for the for-loop (esp. the first statement)
ifAst = ast.If(body=[], orelse=[], test=ast.Name(id="True", ctx=ast.Load()))
funcEnv.pushScope(ifAst.body)
cStatementToPyAst(funcEnv, stmnt.args[0])
whileAst = ast.While(body=[], orelse=[], test=ast.Name(id="True", ctx=ast.Load()))
ifAst.body.append(whileAst)
ifTestAst = ast.If(body=[ast.Pass()], orelse=[ast.Break()])
ifTestAst.test = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, *astAndTypeForCStatement(funcEnv, stmnt.args[1]))
whileAst.body.append(ifTestAst)
funcEnv.pushScope(whileAst.body)
if stmnt.body is not None:
cCodeToPyAstList(funcEnv, stmnt.body)
cStatementToPyAst(funcEnv, stmnt.args[2])
funcEnv.popScope() # whileAst / main for-body
funcEnv.popScope() # ifAst
return ifAst
def astForCDoWhile(funcEnv, stmnt):
assert isinstance(stmnt, CDoStatement)
assert isinstance(stmnt.whilePart, CWhileStatement)
assert stmnt.whilePart.body is None
assert len(stmnt.args) == 0
assert len(stmnt.whilePart.args) == 1
assert isinstance(stmnt.whilePart.args[0], CStatement)
whileAst = ast.While(body=[], orelse=[], test=ast.Name(id="True", ctx=ast.Load()))
funcEnv.pushScope(whileAst.body)
if stmnt.body is not None:
cCodeToPyAstList(funcEnv, stmnt.body)
funcEnv.popScope()
ifAst = ast.If(body=[ast.Continue()], orelse=[ast.Break()])
ifAst.test = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, *astAndTypeForCStatement(funcEnv, stmnt.whilePart.args[0]))
whileAst.body.append(ifAst)
return whileAst
def astForCIf(funcEnv, stmnt):
assert isinstance(stmnt, CIfStatement)
assert len(stmnt.args) == 1
assert isinstance(stmnt.args[0], CStatement)
ifAst = ast.If(body=[], orelse=[])
ifAst.test = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, *astAndTypeForCStatement(funcEnv, stmnt.args[0]))
funcEnv.pushScope(ifAst.body)
if stmnt.body is not None:
cCodeToPyAstList(funcEnv, stmnt.body)
if not ifAst.body: ifAst.body.append(ast.Pass())
funcEnv.popScope()
if stmnt.elsePart is not None:
assert stmnt.elsePart.body is not None
funcEnv.pushScope(ifAst.orelse)
cCodeToPyAstList(funcEnv, stmnt.elsePart.body)
if not ifAst.orelse: ifAst.orelse.append(ast.Pass())
funcEnv.popScope()
return ifAst
def astForCSwitch(funcEnv, stmnt):
assert isinstance(stmnt, CSwitchStatement)
assert isinstance(stmnt.body, CBody)
assert len(stmnt.args) == 1
assert isinstance(stmnt.args[0], CStatement)
# introduce dummy 'if' AST so that we can return a single AST node
ifAst = ast.If(body=[], orelse=[], test=ast.Name(id="True", ctx=ast.Load()))
funcEnv.pushScope(ifAst.body)
switchVarName = funcEnv.registerNewVar("_switchvalue")
switchValueAst, switchValueType = astAndTypeForCStatement(funcEnv, stmnt.args[0])
a = ast.Assign()
a.targets = [ast.Name(id=switchVarName, ctx=ast.Store())]
a.value = getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, switchValueAst, switchValueType)
funcEnv.getBody().append(a)
fallthroughVarName = funcEnv.registerNewVar("_switchfallthrough")
a = ast.Assign()
a.targets = [ast.Name(id=fallthroughVarName, ctx=ast.Store())]
a.value = ast.Name(id="False", ctx=ast.Load())
fallthroughVarAst = ast.Name(id=fallthroughVarName, ctx=ast.Load())
funcEnv.getBody().append(a)
# use 'while' AST so that we can just use 'break' as intended
whileAst = ast.While(body=[], orelse=[], test=ast.Name(id="True", ctx=ast.Load()))
funcEnv.getBody().append(whileAst)
funcEnv.pushScope(whileAst.body)
curCase = None
for c in stmnt.body.contentlist:
if isinstance(c, CCaseStatement):
if curCase is not None: funcEnv.popScope()
assert len(c.args) == 1
curCase = ast.If(body=[], orelse=[])
curCase.test = ast.BoolOp(op=ast.Or(), values=[
fallthroughVarAst,
ast.Compare(
left=ast.Name(id=switchVarName, ctx=ast.Load()),
ops=[ast.Eq()],
comparators=[getAstNode_valueFromObj(funcEnv.globalScope.stateStruct, *astAndTypeForCStatement(funcEnv, c.args[0]))]
)
])
funcEnv.getBody().append(curCase)
funcEnv.pushScope(curCase.body)
a = ast.Assign()
a.targets = [ast.Name(id=fallthroughVarName, ctx=ast.Store())]
a.value = ast.Name(id="True", ctx=ast.Load())
funcEnv.getBody().append(a)
elif isinstance(c, CCaseDefaultStatement):
if curCase is not None: funcEnv.popScope()
curCase = ast.If(body=[], orelse=[])
curCase.test = ast.UnaryOp(op=ast.Not(), operand=fallthroughVarAst)
funcEnv.getBody().append(curCase)
funcEnv.pushScope(curCase.body)
else:
assert curCase is not None
cStatementToPyAst(funcEnv, c)
if curCase is not None: funcEnv.popScope()
# finish 'while'
funcEnv.getBody().append(ast.Break())
funcEnv.popScope()
# finish 'if'
funcEnv.popScope()
return ifAst
def astForCReturn(funcEnv, stmnt):
assert isinstance(stmnt, CReturnStatement)
if not stmnt.body:
assert isSameType(funcEnv.globalScope.stateStruct, funcEnv.func.type, CVoidType())
return ast.Return(value=None)
assert isinstance(stmnt.body, CStatement)
valueAst, valueType = astAndTypeForCStatement(funcEnv, stmnt.body)
returnValueAst = getAstNode_newTypeInstance(funcEnv.interpreter, funcEnv.func.type, valueAst, valueType)
return ast.Return(value=returnValueAst)
def cStatementToPyAst(funcEnv, c):
body = funcEnv.getBody()
if isinstance(c, (CVarDecl,CFunc)):
funcEnv.registerNewVar(c.name, c)
elif isinstance(c, CStatement):
a, t = astAndTypeForCStatement(funcEnv, c)
if isinstance(a, ast.expr):
a = ast.Expr(value=a)
body.append(a)
elif isinstance(c, CWhileStatement):
body.append(astForCWhile(funcEnv, c))
elif isinstance(c, CForStatement):
body.append(astForCFor(funcEnv, c))
elif isinstance(c, CDoStatement):
body.append(astForCDoWhile(funcEnv, c))
elif isinstance(c, CIfStatement):
body.append(astForCIf(funcEnv, c))
elif isinstance(c, CSwitchStatement):
body.append(astForCSwitch(funcEnv, c))
elif isinstance(c, CReturnStatement):