/
jsrewriter.py
executable file
·2055 lines (1796 loc) · 67 KB
/
jsrewriter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ft=python ts=4 sw=4 sts=4 et fenc=utf-8
# Original author: "Eivind Magnus Hvidevold" <hvidevold@gmail.com>
# License: GNU GPLv3 at http://www.gnu.org/licenses/gpl.html
'''
'''
import os
import sys
import re
import argparse
import json
from collections import Counter
import collections
scriptPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(scriptPath, 'addict'))
from addict import Dict
halfLingASTMap = {
'ASTRootNode': 'root',
'TranslationUnitDecl': 'file',
'TypedefDecl': 'tdef',
'FunctionDecl': 'defn',
'IfStmt': '_if',
'ArraySubscriptExpr': 'subscript',
'RecordDecl': 'rec',
'CompoundStmt': 'compound',
'DeclStmt': 'decl',
'VarDecl': 'def',
'ImplicitCastExpr': 'c',
'DeclRefExpr': 'ref',
'ForStmt': '_for',
'BinaryOperator': 'op',
'UnaryOperator': 'up',
'ReturnStmt': 'ret',
'IntegerLiteral': 'i',
'NullStmt': 'null',
None: 'null',
'CStyleCastExpr': 'cc',
'EnumDecl': 'enum',
'EnumConstantDecl': 'edecl',
'CompoundAssignOperator': 'assign',
'ParenExpr': 'p',
'WhileStmt': '_while',
'SwitchStmt': '_switch',
'CaseStmt': '_case',
'BreakStmt': '_break',
'DefaultStmt': '_default',
'CallExpr': 'call',
'StringLiteral': 'str',
'MemberExpr': 'm',
'UnaryExprOrTypeTraitExpr': 'sz',
'InitListExpr': 'init',
'VAArgExpr': 'va',
'jsfun': 'jsfun',
'val': 'val',
'new': '_new',
'FieldDecl': 'field',
'typed_array': 'typed_array',
'fill_array': 'fill_array',
'fill_string': 'fill_string',
'null_ptr': 'null_ptr'
}
defaultValues = {
'int': '0',
'char': '0',
'short': '0',
'long': '0',
'long long': '0',
'float': '0.0',
'double': '0.0'
}
JSBUILTINS = '''break
case
class
catch
const
continue
debugger
default
delete
do
else
export
extends
finally
for
function
if
import
in
instanceof
let
new
return
super
switch
this
throw
try
typeof
var
void
while
with
yield'''.splitlines()
BUILTINS = '''getSaveLine
_l
_r1
_r2
_r3
_n
C
'''.splitlines()
def indent(s):
# indent all
s = re.sub(r'^', ' ', s, flags=re.MULTILINE)
# but not blank lines
s = re.sub(r'^\s*$', '', s, flags=re.MULTILINE)
return s
class Util(object):
@staticmethod
def isPrimitive(typeName):
return typeName.split(' ')[-1] in [
'int',
'long',
'char',
'short',
'float',
'double'
]
class SourceExtent(object):
def __init__(self, start, end):
self.start = start
self.end = end
class SourceLocation(object):
def __init__(self, filename, line, col, valid):
self.filename = filename
self.line = line
self.col = col
self.valid = valid
def __str__(self):
return str(self.filename) + ':' + str(self.line) + ':' + str(self.col) + ':' + str(self.valid)
class HalfLingNode(object):
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], ASTNode):
astNode = args[0]
self.kind = astNode.kind
assert self.kind in halfLingASTMap, "halfling not there: " + str(astNode.__class__) + " " + str(self.kind)
self.children = []
else:
[astNode, kind, children] = args
self.kind = kind
self.children = children
self.debugInfo = Dict()
self.info = Dict()
def serialize(self):
self.fun = 'I.' + halfLingASTMap[self.kind]
debugJSON = json.dumps(self.debugInfo)
infoJSON = json.dumps(self.info)
s = 'serializing halfling %s' % (str(self.kind))
print s
children = []
for child in self.children:
if isinstance(child, HalfLingNullNode):
continue
elif isinstance(child, HalfLingNode):
children.append(child.serialize())
elif not isinstance(child, basestring) and isinstance(child, collections.Sequence):
print self.children
print child
raise Exception("child should not be a list")
else:
children.append(json.dumps(child))
childrenJSON = ',\n'.join(children)
childrenJSON = indent(childrenJSON)
s = '%s(%s, %s, \n[%s])' % (self.fun, debugJSON, infoJSON, childrenJSON)
if self.kind == 'ASTRootNode':
s = 'programs[programCounter++] = ' + s
return s
class HalfLingNullPointer(HalfLingNode):
def __init__(self, astNode):
super(HalfLingNullPointer, self).__init__(astNode, 'null_ptr', [])
class HalfLingFillString(HalfLingNode):
def __init__(self, astNode, args):
super(HalfLingFillString, self).__init__(astNode, 'fill_string', args)
class HalfLingFillArray(HalfLingNode):
def __init__(self, astNode, args):
super(HalfLingFillArray, self).__init__(astNode, 'fill_array', args)
class HalfLingTypedArray(HalfLingNode):
def __init__(self, astNode, args):
super(HalfLingTypedArray, self).__init__(astNode, 'typed_array', args)
class HalfLingNew(HalfLingNode):
def __init__(self, astNode, recName, args):
super(HalfLingNew, self).__init__(astNode, 'new', [recName] + args)
class HalfLingJSFun(HalfLingNode):
def __init__(self, astNode, fName, args):
super(HalfLingJSFun, self).__init__(astNode, 'jsfun', [fName] + args)
class HalfLingRef(HalfLingNode):
def __init__(self, astNode, varName):
super(HalfLingRef, self).__init__(astNode, 'DeclRefExpr', [varName])
class HalfLingRValueRef(HalfLingNode):
def __init__(self, astNode, varName):
super(HalfLingRValueRef, self).__init__(astNode, 'ImplicitCastExpr', [])
self.children = [HalfLingRef(astNode, varName)]
self.info.l2r = True
class HVal(HalfLingNode):
def __init__(self, astNode, value):
super(HVal, self).__init__(astNode, 'val', [value])
class HalfLingNullNode(object):
def __init__(self, astNode):
self.astNode = astNode
class ASTNode(object):
def __init__(self, opts):
for key in opts.keys():
self.__dict__[key] = opts[key]
self.children = []
self._extent = None
def printParents(self):
stack = []
parent = self.parent
while parent.kind != 'ASTRootNode':
stack.append(parent)
parent = parent.parent
stack.reverse()
for parent in stack:
print 'parent line', parent.rawline
print 'self line', self.rawline
# TODO: move to Util
def isID(self, expr):
return re.search('^[A-Za-z0-9_]+$', expr)
def find(self, filter):
if filter(self):
yield self
for child in self.children:
for found in child.find(filter):
yield found
def filterTrash(self, node):
return node.kind == None or isinstance(node, ASTAttr)
def getPosition(self):
return [i for i, x in enumerate(self.parent.children) if x == self][0]
def getChildrenRecursive(self, childFilter=None):
for child in self.children:
yield child
if childFilter == None or childFilter(child):
for grandChild in child.getChildrenRecursive(childFilter):
yield grandChild
def getVarNames(self, childFilter=None):
'get all variable names for moving them up in the hierarchy'
def getVarNamesH(node, compoundParent):
if node.kind == "CompoundStmt":
compoundParent = node
compoundParent.variables = []
elif node.kind == "VarDecl" and node.declared == False:
varName = node.getVarName()
varNames[varName] = True
counter[varName] += 1
if counter[varName] > 1:
shadowVars = True
compoundParent.variables.append(node)
variables.append(node)
for child in node.children:
if childFilter == None or childFilter(child):
getVarNamesH(child, compoundParent)
if node.kind == "CompoundStmt":
for var in compoundParent.variables:
varName = node.getVarName()
counter[varName] -= 1
counter = Counter()
shadowVars = False
variables = []
varNames = {}
getVarNamesH(self, None)
varNames = varNames.keys()
if len(varNames) > 0:
statement = 'var ' + ', '.join(varNames) + ';\n'
else:
statement = ''
return {'varNames': varNames,
'statement': statement,
'variables': variables,
'shadowVars': shadowVars}
def getOperator(self):
return self.rest.split(' ')[-1].strip("'")
def getMember(self):
return self.rest.split(' ')[-2].strip("'")
def getChildValues(self, sep=''):
s = ''
for child in self.children:
value = child.getValue()
assert value != None, child.kind
s += value + sep
return s
# TODO: static, could be moved to Util
def getBracketNum(self, s):
return re.search('\[([0-9]+)\]', s).group(1)
def getValue(self):
print 'warning, default handler for: ', self.kind
return self.getChildValues()
def halfLingChildren(self):
children = [x.halfLing() for x in self.children if not self.filterTrash(x)]
return children
def halfLing(self):
print 'warning, default halfling handler for: ', self.kind
h = HalfLingNode(self)
h.children = self.halfLingChildren()
return h
def getVarName(self):
varNames = filter(lambda x: x[0] == '[0;1;36', self.lineByColor)
if len(varNames) > 0:
varName = varNames[0][1]
varName = varName.strip()
varName = varName.strip("'")
if varName in self.root.builtins:
print "Renamed var", varName
varName = varName + '_'
else:
varName = None
return varName
def getVarType(self):
varType = filter(lambda x: x[0] == '[0;32', self.lineByColor)[0][1]
varType = varType.strip("'")
return varType
def getLastVarType(self):
varType = filter(lambda x: x[0] == '[0;32', self.lineByColor)[-1][1]
varType = varType.strip("'")
return varType
def parseLocation(self, location, askParent):
match = re.search('^col:(?P<col>[0-9]+)$', location)
match2 = re.search('^((?P<fname>[^:]+):)?(?P<line>[0-9]+):(?P<col>[0-9]+)$', location)
match3 = re.search('<invalid sloc', location)
if match:
filename = None
line = None
if askParent:
extent = self.parent.getExtent()
#parent = self.parent
#while parent.kind != 'root':
# print 'parent line', parent.rawline
# parent = parent.parent
filename = extent.start.filename #or extent.end.filename
line = extent.start.line #or extent.end.line
col = int(match.group('col')) - 1 # 0 indexed
valid = True
elif match2:
filename = match2.group('fname')
if filename == 'line':
if askParent:
filename = self.parent.getExtent().start.filename
else:
filename = None
line = int(match2.group('line')) - 1 # 0 indexed
col = int(match2.group('col')) - 1 # 0 indexed
valid = True
elif match3:
filename = None
line = None
col = None
valid = False
else:
assert False, location
return SourceLocation(filename, line, col, valid)
def getExtent(self):
if self._extent:
return self._extent
match = re.search(r'^<(.*), (.*)>$', self.location)
match2 = re.search(r'^<(.*)>$', self.location)
if match or match2:
if match:
startLocation = match.group(1)
start = self.parseLocation(startLocation, True)
endLocation = match.group(2)
end = self.parseLocation(endLocation, False)
elif match2:
startLocation = match2.group(1)
start = self.parseLocation(startLocation, True)
end = start
if start.filename == None:
start.filename = self.root.filename
if end.filename == None:
end.filename = start.filename
if end.line == None:
end.line = start.line
self._extent = SourceExtent(start, end)
return self._extent
else:
assert False, self.line + ", LOCATION: " + self.location
def getLineLocation(self):
match = re.search('<line:([0-9]+)', self.location)
if match:
return int(match.group(1))
else:
return None
def getLogStatement(self, extra):
extent = self.getExtent()
s = '_log("%s:%s at %s:%s:%s = %s\\n");\n' % (
str(self.kind),
str(self.getVarName()),
str(extent.start.filename),
str(extent.start.line),
str(extent.start.col),
extra)
return s
def rewrite(self, replacer):
pass
class ASTRootNode(ASTNode):
def __init__(self):
self.kind = 'ASTRootNode'
self.prefix = ''
self.location = 0
self.children = []
self.builtins = JSBUILTINS + BUILTINS
self.externs = {}
self.typedefs = {}
self.records = {}
def getValue(self):
return self.getChildValues()
def getLastType(self, typeName):
if "':'" in typeName:
typeName = typeName.split("':'")[-1].strip("'")
return typeName
def resolveType(self, typeName):
old = None
typeName = self.getLastType(typeName)
while typeName in self.typedefs and old != typeName:
old = typeName
typeName = self.typedefs[typeName]
typeName = self.getLastType(typeName)
return typeName
def resolvePrimType(self, varType):
primType = varType
old = None
while primType != old:
old = primType
primType = self.removeGeneralType(primType)
primType = self.removeLengthSpecifier(primType)
primType = self.removeSignSpecifier(primType)
primType = self.removeOtherSpecifiers(primType)
primType = self.resolveType(primType)
primType = self.removeGeneralType(primType)
primType = self.removeLengthSpecifier(primType)
primType = self.removeSignSpecifier(primType)
primType = self.removeOtherSpecifiers(primType)
return primType
def getHalfLingDefaultInitializer(self, varType):
if '*' in varType:
initializer = HalfLingNullPointer(self)
else:
varType = self.resolveType(varType)
#print 'resolve: ', varType
primType = self.removeSignSpecifier(varType) #.split(' ')[-1]
# TODO: multidim arrays
arraySize = self.getLengthSpecifier(varType)
if arraySize:
primType = self.resolvePrimType(varType)
#print "array", varType, primType, arraySize
if primType in defaultValues:
defaultValue = defaultValues[primType]
#initializer = 'C.fillArray(%s, %d)' % (defaultValue, arraySize)
args = [HVal(self, defaultValue), HVal(self, arraySize)]
initializer = HalfLingFillArray(self, args)
else:
if primType == '__va_list_tag':
args = [HalfLingRValueRef(self, primType)]
initializer = HalfLingJSFun(self, 'C.create', args)
else:
assert primType != 'void'
args = [HalfLingRValueRef(self, primType), HVal(self, arraySize)]
initializer = HalfLingTypedArray(self, args)
elif primType in defaultValues:
initializer = HVal(self, defaultValues[primType])
else:
recordName = self.removeGeneralType(varType)
initializer = HalfLingNew(self, recordName, [])
return initializer
def getDefaultInitializer(self, varType):
if '*' in varType:
initializer = '_n'
else:
varType = self.resolveType(varType)
#print 'resolve: ', varType
primType = self.removeSignSpecifier(varType) #.split(' ')[-1]
# TODO: multidim arrays
arraySize = self.getLengthSpecifier(varType)
if arraySize:
primType = self.resolvePrimType(varType)
#print "array", varType, primType, arraySize
if primType in defaultValues:
defaultValue = defaultValues[primType]
initializer = 'C.fillArray(%s, %d)' % (defaultValue, arraySize)
else:
if primType == '__va_list_tag':
initializer = 'new %s()' % (primType)
else:
assert primType != 'void'
initializer = 'C.typedArray(%s, %d)' % (primType, arraySize)
elif primType in defaultValues:
initializer = defaultValues[primType]
else:
initializer = 'new %s()' % self.removeGeneralType(varType)
return initializer
def removeOtherSpecifiers(self, varType):
return re.sub('(const)\s*', '', varType)
def removeSignSpecifier(self, varType):
return re.sub('((signed)|(unsigned))\s*', '', varType)
def removeGeneralType(self, varType):
return re.sub('((union)|(enum)|(struct))\s*', '', varType)
def removeLengthSpecifier(self, varType):
return re.sub('\s*\[([0-9]+)\]', '', varType)
def getLengthSpecifier(self, varType):
match = re.search('\[([0-9]+)\]', varType)
if match:
match = int(match.group(1))
return match
def renameField(self, field):
if field in ['_s1', 'length']:
print 'renaming field: %s' % field
field = field + '_'
return field
class ASTNullNode(ASTNode):
# too lazy to define __init__ and call super
def init(self):
self.kind = None
def getValue(self):
return ''
class ASTArrayFiller(ASTNode):
# too lazy to define __init__ and call super
def init(self):
self.kind = "ASTArrayFiller"
self.children = []
class ASTAttr(ASTNode):
"usually we don't care about it"
def getValue(self):
assert len(self.children) == 0
return ''
class AlwaysInlineAttr(ASTAttr):
pass
class ArraySubscriptExpr(ASTNode):
def getValue(self):
c1, c2 = self.children
val1 = c1.getValue()
val2 = c2.getValue()
return '%s._s1(%s).x' % (val1, val2)
class AsmLabelAttr(ASTAttr): pass
class BinaryOperator(ASTNode):
def overridePointerArithmetic(self, c1, c2, val1, val2, t1, t2, operator):
ptr = False
hasPtr = False
if '*' in t1:
ptr = val1
other = val2
otherAsPtr = ''
hasPtr = True
switched = False
elif '*' in t2:
ptr = val2
other = val1
hasPtr = True
switched = True
if '*' in t1 and '*' in t2:
both = True
if hasPtr:
#if operator != '=':
#print 'operator', val1, operator, val2, t1, t2
s = None
if operator == '=':
if 'NullToPointer' in c2.line:
s = '%s = _n' % ptr
return s
#elif c1.kind == "ArraySubscriptExpr":
# c1, c2 = self.children
# val1 = c1.getValue()
# val2 = c2.getValue()
# s = '%s._s1(%s)' % (val1, val2)
# return s
# Override pointer arithmetic
elif operator == '==':
s = '%s.eq(%s)'
elif operator == '!=':
s = '%s.ne(%s)'
elif operator == '+':
s = '%s.p(%s)'
elif operator == '-':
s = '%s.m(%s)'
elif operator == '/':
s = '%s.div(%s)'
elif operator == '*':
s = '%s.mul(%s)'
elif operator == '>':
if switched:
s = '%s.lt(%s)'
else:
s = '%s.gt(%s)'
elif operator == '<':
if switched:
s = '%s.gt(%s)'
else:
s = '%s.lt(%s)'
elif operator == '>=':
if switched:
s = '%s.le(%s)'
else:
s = '%s.ge(%s)'
elif operator == '<=':
if switched:
s = '%s.ge(%s)'
else:
s = '%s.le(%s)'
elif operator == ',':
s = None
else:
assert False, ('BINARY PTR OPERATOR', operator)
if s != None:
return s % (ptr, other)
return None
def halfLing(self):
h = HalfLingNode(self)
operator = self.getOperator()
h.children = [operator] + [x.halfLing() for x in self.children]
return h
def getValue(self):
c1, c2 = self.children
val1 = c1.getValue()
val2 = c2.getValue()
operator = self.getOperator()
t1, t2 = c1.getVarType(), c2.getVarType()
s = self.overridePointerArithmetic(c1, c2, val1, val2, t1, t2, operator)
if s != None:
return s
s = '%s %s %s' % (val1, operator, val2)
if operator in ['+', '-', '*', '/']:
# coerce to int32
s = '((%s) >>> 0)' % s
return s
class BreakStmt(ASTNode):
def getValue(self):
return 'break;\n'
class CallExpr(ASTNode):
def overrideFunctions(self, fexpr, fexprValue, values):
allocs = ['alloc', 'malloc']
s = None
typeCheck = True
if (fexprValue in allocs):
if ((self.parent.kind == "CStyleCastExpr" or
self.parent.kind == "ImplicitCastExpr") and
not 'void' in self.parent.getVarType()):
varType = self.parent.getVarType()
else:
# Will be return type of alloc function, like char_u or void*,
# but looks like result is of same type.
varType = self.getVarType()
if '*' in varType:
primType = self.root.resolvePrimType(varType.strip(' *'))
sizeExpr = values[0]
if primType in defaultValues:
defaultValue = defaultValues[primType]
if primType == 'char':
s = 'C.fillString(%s, %s)' % (defaultValue, sizeExpr)
else:
s = 'C.fillArray(%s, %s)' % (defaultValue, sizeExpr)
else:
assert primType != 'void'
s = 'C.typedArray(%s, %s)' % (primType, sizeExpr)
else:
initializer = self.root.getDefaultInitializer(varType)
s = initializer
return [s, fexprValue, typeCheck]
elif fexprValue == 'calloc':
assert False, 'not implemented'
elif fexprValue == 'printf':
fexprValue = '_printf'
elif fexprValue == 'puts':
fexprValue = '_puts'
elif fexprValue == 'memset':
# XXX: hack
fexprValue = 'fakememset'
elif fexprValue == '__builtin_va_start':
fexprValue = '__va_list_start'
values = ['arguments'] + values
typeCheck = False
elif fexprValue == '__builtin_va_end':
fexprValue = '__va_list_end'
typeCheck = False
return [s, fexprValue, typeCheck]
def getValue(self):
fexpr = self.children[0]
fexprValue = fexpr.getValue()
childExpr = self.children[1:]
values = [x.getValue() for x in childExpr]
types = [self.getVarType()] + [x.getVarType() for x in childExpr]
for i, tp in enumerate(types):
if re.search('\*[^(]*\([^)]\)', tp):
tp = 'function'
elif '*' in tp:
tp = 'ptr'
else:
tp = self.root.resolvePrimType(tp.strip(' *'))
if not self.isID(tp):
assert False, tp
types[i] = tp
varName = fexpr.getVarName()
quotedTypes = ['"' + x + '"' for x in types]
[s, fexprValue, typeCheck] = self.overrideFunctions(fexpr, fexprValue, values)
if s:
return s
if typeCheck:
if len(values) > 0:
values = [''] + values # for starting ,
#print 'types', quotedTypes
s = 'C.typeCheckCall("%s", [%s] %s)' % (fexprValue, ', '.join(quotedTypes), ', '.join(values))
else:
s = '%s(%s)' % (fexprValue, ', '.join(values))
#print 'call ', s
return s
def halfLing(self):
h = HalfLingNode(self)
fexpr = self.children[0]
fexprValue = fexpr.getValue()
h.children = self.halfLingChildren()
print 'fexprValue', fexprValue
if fexprValue in ['malloc', 'alloc']:
if ((self.parent.kind == "CStyleCastExpr" or
self.parent.kind == "ImplicitCastExpr") and
not 'void' in self.parent.getVarType()):
varType = self.parent.getVarType()
else:
# Will be return type of alloc function, like char_u or void*,
# but looks like result is of same type.
varType = self.getVarType()
if '*' in varType:
primType = self.root.resolvePrimType(varType.strip(' *'))
sizeExpr = self.children[1].halfLing()
if primType in defaultValues:
defaultValue = defaultValues[primType]
if primType == 'char':
args = [HVal(self, defaultValue), sizeExpr]
initializer = HalfLingFillString(self, args)
else:
args = [HVal(self, defaultValue), sizeExpr]
initializer = HalfLingFillArray(self, args)
else:
assert primType != 'void'
args = [HVal(self, defaultValue), sizeExpr]
initializer = HalfLingTypedArray(self, args)
else:
initializer = self.root.getHalfLingDefaultInitializer(varType)
return initializer
if fexprValue in ['printf', 'puts', 'time']:
h.kind = 'jsfun'
h.children[0] = fexprValue
elif h.children[0].kind == 'ImplicitCastExpr':
h.children[0].info.l2r = True
return h
class CaseStmt(ASTNode):
def getValue(self):
test = self.children[0].getValue()
assert self.children[1].kind == None
body = self.children[2].getValue()
s = 'case %s:\n' % test
s += indent(body)
s += '\n'
return s
class CharacterLiteral(ASTNode):
def getValue(self):
return self.getVarName()
class CompoundAssignOperator(ASTNode):
def getOperator(self):
operator = re.search("'([^']+)' ComputeLHSTy", self.rest).group(1)
#return self.rest.split(' ')[-3].strip("'")
return operator
def getValue(self):
c1, c2 = self.children
val1 = c1.getValue()
val2 = c2.getValue()
operator = self.getOperator()
#print 'operator', operator
return '%s %s %s' % (val1, operator, val2)
class CompoundStmt(ASTNode):
def getValue(self):
#return '{' + self.getChildValues(';\n') + '}'
s = ''
result = self.getVarNames(lambda y: y.kind != "CompoundStmt")
s += result['statement']
for child in self.children:
s += child.getValue()
s = re.sub(r'\s*;', ';', s);
ss = s.rstrip()
if not ss.endswith('}') and not ss.endswith(';'):
s += ';\n'
if self.parent.kind != 'SwitchStmt':
wrap = '{' + s + '}'
else:
wrap = s
return wrap
class ConditionalOperator(ASTNode):
def getValue(self):
condition, expr1, expr2 = self.children
condition = condition.getValue()
expr1 = expr1.getValue()
#if ';' in expr1:
# expr1 = '( %s )' % expr1
expr2 = expr2.getValue()
#if ';' in expr2:
# expr2 = '( %s )' % expr2
s = '%s ? %s : %s' % (condition, expr1, expr2)
#print 'conditional', s
return s
class ConstAttr(ASTAttr): pass
class ContinueStmt(ASTNode):
def getValue(self):
return 'continue;\n'
class CStyleCastExpr(ASTNode):
def getValue(self):
return self.getChildValues()
class DeclRefExpr(ASTNode):
def halfLing(self):
h = HalfLingNode(self)
h.children = [self.getVarName()]
return h
def getValue(self):
varname = self.getVarName()
return varname
class DeclStmt(ASTNode):
def getValue(self):
# TODO: maybe sep=; but not in for loops
return self.getChildValues('')
class DefaultStmt(ASTNode):
def getValue(self):
body = self.children[0].getValue()
assert len(self.children) == 1
s = 'default:\n'
s += indent(body)
s += '\n'
return s
class DeprecatedAttr(ASTAttr): pass
class DoStmt(ASTNode):
def getValue(self):
assert len(self.children) == 2
body = self.children[0].getValue()
test = self.children[1].getValue()
s = 'do {\n'
s += indent(body)
s += '\n} while (%s);\n' % test
return s
class EmptyDecl(ASTNode): pass
class EnumConstantDecl(ASTNode):
def getValue(self):
return self.getChildValues()
class EnumDecl(ASTNode):
def getValue(self):
s = ''
oldValue = None
i_base = 0
i = 0
for child in self.children:
if len(child.children) > 0:
value = child.getValue()
try:
i_base = int(value)
except ValueError, e:
i_base = value
i = 0
else:
if isinstance(i_base, int):
value = str(i_base + i)
else:
value = i_base + ' + ' + str(i)
i += 1
s += 'var %s = %s;\n' % (child.getVarName(), value)
return s
# Handled as part of RecordDecl
class FieldDecl(ASTNode):
def halfLing(self):