-
Notifications
You must be signed in to change notification settings - Fork 18
/
Generator.py
1813 lines (1437 loc) · 52.4 KB
/
Generator.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
# FuzzerFactory
import re
import argparse
import os
import json
import copy
from Config import *
#from InputGeneration import *
from Utils import *
# Grammar Format
"""
select_statement:
SELECT column_name FROM table_name {xxxxx}
SELECT column_list FROM table_name JOIN table_name {xxxxxx}
-------------------------------------------------------------
create_statement:
CREATE xxx
-------------------------------------------------------------
"""
allClass = list()
tokenDict = dict()
#notKeywordSym = dict()
literalValue = dict() #{"float":["float_literal"], "int":["int_literal"], "string":["identifier", "string_literal"]}
destructorDict = dict()
gDataFlagMap = dict()
gDataFlagMap["Define"] = 1
gDataFlagMap["Undefine"] = 2
gDataFlagMap["Global"] = 4
gDataFlagMap["Use"] = 8
gDataFlagMap["MapToClosestOne"] = 0x10
gDataFlagMap["MapToAll"] = 0x20
gDataFlagMap["Replace"] = 0x40
gDataFlagMap["Alias"] = 0x80
gDataFlagMap["NoSplit"] = 0x100
gDataFlagMap["ClassDefine"] = 0x200
gDataFlagMap["FunctionDefine"] = 0x400
gDataFlagMap["Insertable"] = 0x800
#gDataFlagMap["VarDefine"] = 0x800
#gDataFlagMap["VarType"] = 0x1000
#gDataFlagMap["VarName"] = 0x2000
semanticRule = None
def is_specific(classname):
'''
test if this class need specific handling
return [bool, type]
e.g. [Flase, ""] or [True, "string"]
'''
classname = hump_to_underline(classname)
global literalValue
flag = False
for k, v in literalValue.items():
for cname in v:
if(cname == classname):
return [True, k]
return [False, ""]
def expect():
id = [0]
def func():
id[0] += 1
return 'v' + str(id[0])
return func
'''
DataTypeRule:
path: list[] of string
datatype: string
Token:
token_name: string
prec : int
association: string
match_string: string
is_keyword: bool
Symbol: class
name: string
isTerminator: bool
isId: bool
Case: class
caseidx: int
symbolList:
idTypeList:
GenClass: class
name: string
memberList : dict # A dictionary of this class's members
caseList : list of case # A list of each case of this class
'''
class DataTypeRule:
def __init__(self, path, datatype, scope, dataflag):
self.path = path
self.datatype = datatype
self.scope = int(scope)
flag = 0
for i in dataflag:
flag |= gDataFlagMap[i]
self.dataflag = flag
class Token:
def __init__(self, token_name, prec, assoc, match_string, ttype):
self.token_name = token_name
self.prec = prec
self.assoc = assoc
self.ttype = ttype
self.match_string = match_string
self.is_keyword = (token_name == match_string)
class Symbol:
def __init__(self, name, isTerminator = False, isId = False):
self.name = name
self.isTerminator = isTerminator
self.isId = isId
self.analyze()
def analyze(self):
token = self.analyze_item(self.name)
if(token == "_COMMA_" or token == "_QUOTA_" or token == "_LD_" or token == "_RD_" or "_QUEAL_"):
self.name = self.name.replace("\'", "")
if(self.name.isupper()):
self.isTerminator = True
if(token == "_IDENTIFIER_"):
#self.isTerminator = False
self.isId = True
def analyze_item(self, i):
if i == "IDENTIFIER":
return "_IDENTIFIER_"
elif i == "EMPTY":
return "_EMPTY_"
elif i == "'='":
return "_EQUAL_"
elif i == "','":
return "_COMMA_"
elif i == "';'":
return "_QUOTA_"
elif i == "'('":
return "_LD_"
elif i == "')'":
return "_RD_"
elif i.isupper():
return "_KEYWORD_"
else:
return "_VAR_"
def __str__(self):
return "name:%s, isTerminator:%s, isId:%s" % (self.name, self.isTerminator, self.isId)
class Case:
def __init__(self, caseidx, isEmpty, prec, data_type_to_replace, expected_value_generator=expect()):
self.caseidx = caseidx
self.symbolList = list()
self.idTypeList = list()
self.isEmpty = isEmpty
self.prec = prec
self.datatype_rules = self.parse_datatype_rules(data_type_to_replace)
def parse_datatype_rules(self, s):
res = []
if s == None:
return res
s = s.split(";")
for i in s:
#print(i)
if i.strip() == "":
continue
i = i.split("=")
path = i[0].strip().split("->")
prop = i[1].strip().split(":")
res.append(DataTypeRule(path, prop[0], prop[1], prop[2:]))
return res
def gen_member_list(self):
member_list = {}
member_list.clear()
#if empty, we won't add anything into memberlist
if(self.isEmpty == True):
return member_list
for s in self.symbolList:
if s.isTerminator == True:
continue
if(s.name in member_list):
member_list[s.name] += 1
else:
member_list[s.name] = 1
return member_list
def __str__(self):
symbol = ""
for i in self.symbolList:
symbol += "(" + str(i) + ")" + ","
symbol = symbol[:-1]
res = "caseidx:%d, SymbolList:(%s), isEmpty:%s, prec: %s\n" % (self.caseidx, symbol, self.isEmpty, self.prec)
return res
class Genclass:
def __init__(self, name, memberList = None, caseList = None):
if(memberList == None):
memberList = dict()
if(caseList == None):
caseList = list()
self.name = underline_to_hump(name)
self.memberList = memberList
self.caseList = list()
self.isTerminatable = False
def merge_member_list(self, current_member_list):
for m in current_member_list:
if(m in self.memberList and current_member_list[m]>self.memberList[m]):
self.memberList[m] = current_member_list[m]
elif(m not in self.memberList):
self.memberList[m] = current_member_list[m]
def __str__(self):
name = self.name
members = "("
for k, v in self.memberList.items():
members += k + ":" + str(v) + ","
members = members[:-1] + ")"
case = "("
for i in self.caseList:
case += str(i) + ","
case = case[:-1] + ")"
return "Genclass:[name:%s,\n memberList:%s,\n caseList:%s]" %(name, members, case)
def handle_datatype(vvlist, data_type, scope, dataflag, gen_name, tnum = 0):
tab = "\t"
vlist = [i[0] for i in vvlist]
if(len(vlist) == 1):
if('fixme' in vlist[0]):
vlist[0] = '$$'
res = tab*tnum + "if(%s){\n" % vlist[0]
res += tab*(tnum+1) + "%s->data_type_ = %s; \n" %(vlist[0], data_type)
res += tab*(tnum+1) + "%s->scope_ = %d; \n" %(vlist[0], scope)
res += tab*(tnum+1) + "%s->data_flag_ =(DATAFLAG)%d; \n" %(vlist[0], dataflag)
res += tab*tnum + "}\n"
return res
if(is_list(vvlist[0][1]) == False):
res = ""
if(len(vlist) == 2 and vlist[1] == "fixme"):
res += handle_datatype(vvlist[1:], data_type, scope, dataflag, gen_name, tnum)
else:
tmp_name = gen_name()
res = tab*tnum + "if(%s){\n" % vlist[0]
res += tab*(tnum+1) + "auto %s = %s->%s_; \n" %(tmp_name, vlist[0], vlist[1])
tmp_list = vvlist[1:]
tmp_list[0][0] = tmp_name
res += handle_datatype(tmp_list, data_type, scope, dataflag, gen_name, tnum+1)
res += tab*tnum + "}\n"
return res
else:
tmp_name = gen_name()
res = tab*(tnum+1) + "auto %s = %s->%s_; \n" %(tmp_name, vlist[0], vlist[1])
tmp_list = vvlist[1:]
tmp_list[0][0] = tmp_name
res += handle_datatype(tmp_list, data_type, scope, dataflag, gen_name, tnum + 1)
loop = tab*tnum + "while(%s){\n" % vlist[0]
loop += res
loop += tab*(tnum+1) + "%s = %s->%s_;\n" %(vvlist[0][0], vvlist[0][0], vvlist[0][1])
loop += tab*tnum + "}\n"
return loop
return res
def genDataTypeOneRule(datatype_rule):
vvlist = [[i, i] for i in datatype_rule.path]
vvlist = [["$$", "$$"]] + vvlist
datatype = datatype_rule.datatype
scope = datatype_rule.scope
dataflag = datatype_rule.dataflag
return handle_datatype(vvlist, datatype, scope, dataflag, gen_tmp(), 2)
def parseGrammar(grammarDescription):
content = grammarDescription.split("\n")
res = Genclass(content[0].strip(":\n"))
#res.memberList = dict()
#print "*************"
#print content[0].strip(":\n")
#print res #this is wrong
#print "*************"
cases = content[1:]
cases = [i.lstrip() for i in cases]
caseIndex = 0
for c in cases:
ptn = re.compile("\*\*.*\*\*")
data_type_to_replace = re.search(ptn, c) #ptn.findall(c)
if(data_type_to_replace != None):
#print("here1")
#print data_type_to_replace.group()
data_type_to_replace = data_type_to_replace.group()[2: -2]
c = re.sub(ptn, '', c)
#print c
tmp_c = (c + "%") .split("%")
c = tmp_c[0].strip()
if(tmp_c[1] != ''):
tmp_c[1] = "%" + tmp_c[1]
case = Case(caseIndex, len(c)==0, tmp_c[1], data_type_to_replace)
caseIndex += 1
symbols = c.split(" ")
case.symbolList = [Symbol(s) for s in symbols]
#print(symbols)
current_member_list = case.gen_member_list()
res.merge_member_list(current_member_list)
res.caseList.append(case)
global allClass
allClass.append(res)
return res
def is_list(class_name):
global allClass
#print class_name#list
class_name = underline_to_hump(class_name)
for i in allClass:
if(class_name == i.name):
for member in i.memberList.keys():
if(underline_to_hump(member) == class_name):
return True
return False
return False
def genClassDef(current_class, parent_class):
'''
Input:
s : class
Output:
definition of this class in cpp: string
'''
res = "class "
res += current_class.name + ":"
res += "public " + "Node "+ "{\n"
res += "public:\n" + "\tvirtual void deep_delete();\n"
res += "\tvirtual IR* translate(vector<IR*> &v_ir_collector);\n"
res += "\tvirtual void generate();\n"
#res += "\t" + current_class.name + "(){type_ = k%s; cout << \" Construct node: %s \\n\" ;}\n" % (current_class.name, current_class.name)
#res += "\t~" + current_class.name + "(){cout << \" Destruct node: %s \\n\" ;}\n" % (current_class.name)
#res += "\t" + current_class.name + "(){}\n"
#res += "\t~" + current_class.name + "(){}\n"
res += "\n"
#Handle classes which need specific variable
specific = is_specific(current_class.name)
if(specific[0]):
res += "\t" + specific[1] + " " + specific[1] + "_val_;\n"
res += "};\n\n"
return res
for member_name, count in current_class.memberList.items():
if(member_name == ""):
continue
if(count == 1):
res += "\t" + underline_to_hump(member_name) + " * " + member_name + "_;\n"
else:
for idx in range(count):
res += "\t" + underline_to_hump(member_name) + " * " + member_name + "_" + str(idx+1) + "_;\n"
res += "};\n\n"
return res
def genDeepDelete(current_class):
res = "void " + current_class.name + "::deep_delete(){\n"
for member_name, count in current_class.memberList.items():
if(count == 1):
res += "\t" + "SAFEDELETE(" + member_name + "_);\n"
else:
for idx in range(count):
res += "\t" + "SAFEDELETE(" + member_name + "_" + str(idx+1) + "_);\n"
res += "\tdelete this;\n"
res += "};\n\n"
return res
def translateOneMember(member_name, variable_name):
"""
Input:
MemberName: string
VariableName: string
Output:
a translate call string
no \t at the front
"""
return "auto " + variable_name + "= SAFETRANSLATE(" + member_name + ");\n"
def findOperator(symbol_list):
res = ""
idx = 0
while(idx < len(symbol_list)):
if(symbol_list[idx].isTerminator == True):
res += get_match_string(symbol_list[idx].name) + " "
symbol_list.remove(symbol_list[idx])
idx -= 1
else:
res = res[:-1]
break
idx += 1
return res.strip()
def get_match_string(token):
#print(token)
if tokenDict.has_key(token) and tokenDict[token].is_keyword == False:
return strip_quote(tokenDict[token].match_string)
return token
def findLastOperator(symbol_list):
res = ""
idx = 0
if(idx < len(symbol_list)):
if(symbol_list[idx].isTerminator == True):
res += get_match_string(symbol_list[idx].name)
symbol_list.remove(symbol_list[idx])
is_case_end = True
for i in range(idx, len(symbol_list)):
if (symbol_list[i].isTerminator == False):
is_case_end = False
break
if(is_case_end == True):
i = 0
while(i < len(symbol_list)):
res += " " + get_match_string(symbol_list[i].name)
symbol_list.remove(symbol_list[i])
res = res.strip()
return res
def findOperand(symbol_list):
res = ""
idx = 0
if(idx < len(symbol_list)):
if(symbol_list[idx].isTerminator == False):
res = symbol_list[idx].name
symbol_list.remove(symbol_list[idx])
else:
print("[*]error occur in findOperand")
exit(0)
return res.strip()
def strip_quote(s):
if(s[0] == '"' and s[-1] == '"'):
return s[1:-1]
return s
def collectOpFromCase(symbol_list):
"""
Input:
case: list
member_list: dict
Output:
(operands, operators): tuple(list, list)
"""
operands = list()
operators = list()
operators.append(findOperator(symbol_list))
operands.append(findOperand(symbol_list))
operators.append(findOperator(symbol_list))
operands.append(findOperand(symbol_list))
operators.append(findLastOperator(symbol_list))
res = ([i for i in operands if i != ""], [i for i in operators])
return res
def translateOneIR(ir_argument, classname, irname):
"""
Input:
0-2 operands, 0-3 operators, classname
Output:
(irname, irstring): tuple(string, string)
"""
operands = ir_argument[0]
operators = ir_argument[1]
for i in range(3):
operators[i] = '"' + operators[i] + '"'
res_operand = ""
for operand in operands:
res_operand += ", " + operand
res_operator = "OP3(" + operators[0] +"," + operators[1] + "," + operators[2] + ")"
#operand_num = len(operands)
if irname != "res":
irname = "auto " + irname
res = irname + " = new IR(" + "k" + underline_to_hump(classname) + ", " + res_operator + res_operand +");\n"
return res
def gen_tmp():
count = [0]
def get_tmp():
count[0] += 1
return "tmp" + str(count[0])
return get_tmp
def transalteOneCase(current_class, case_idx):
current_case = current_class.caseList[case_idx]
member_list = current_class.memberList
symbols = [i for i in current_case.symbolList]
process_queue = list()
name_idx_dict = dict()
res = ""
"""
Handle Empty Case Here
"""
if current_case.isEmpty == True:
return "\t\tres = new IR(k" + underline_to_hump(current_class.name) +", string(\"\"));\n"
for name, count in member_list.items():
if(count > 1):
name_idx_dict[name] = 1
get_tmp = gen_tmp()
for symbol in symbols:
if(symbol.isTerminator == False):
tmp_name = get_tmp()
new_symbol = Symbol(tmp_name, False, symbol.isId)
process_queue.append(new_symbol)
cur_symbol_real_name = ""
if(symbol.name in name_idx_dict.keys()):
cur_symbol_real_name = symbol.name + "_" + str(name_idx_dict[symbol.name]) + "_"
name_idx_dict[symbol.name] += 1
else:
cur_symbol_real_name = symbol.name + "_"
res += "\t\t" + translateOneMember(cur_symbol_real_name, tmp_name)
else:
process_queue.append(symbol)
while(len(process_queue) != 0):
ir_info = collectOpFromCase(process_queue)
if(len(process_queue) == 0):
res += "\t\t" + translateOneIR(ir_info, current_class.name, "res")
else:
tmp_name = get_tmp()
res += "\t\t" + translateOneIR(ir_info, "Unknown", tmp_name)
res += "\t\tPUSH(" + tmp_name + ");\n"
new_symbol = Symbol(tmp_name, False, False)
process_queue = [new_symbol] + process_queue
return res
def genGenerateOneCase(current_class, case_idx):
res = ""
case_list = current_class.caseList[case_idx]
if case_list.isEmpty == True:
return "\n"
counter = dict()
for key in current_class.memberList.keys():
counter[key] = 1
for sym in case_list.symbolList:
if sym.isTerminator:
continue
membername = sym.name+"_"
if(current_class.memberList[sym.name] > 1):
membername = "%s_%d_" % (sym.name, counter[sym.name])
counter[sym.name] += 1
#ddprint(sym.name)
res += "\t\t%s = new %s();\n" %(membername, underline_to_hump(sym.name))
res += "\t\t%s->generate();\n" % membername
return res
def getNotSelfContainCases(current_class):
#print(current_class.name)
mytest_list = {"SimpleSelect":[0, 1, 2, 3], "CExpr": [0], "AExpr": [0]}
if(mytest_list.has_key(current_class.name)):
return mytest_list[current_class.name]
case_idx_list = []
class_name = hump_to_underline(current_class.name)
for case in current_class.caseList:
flag = False
for i in case.symbolList:
if i.name == class_name:
flag = True
break
if flag == False:
case_idx_list.append(case.caseidx)
return case_idx_list
def genGenerate(current_class):
case_nums = len(current_class.caseList)
has_switch = case_nums != 1
class_name = underline_to_hump(current_class.name)
res = "void " + class_name + "::generate(){\n"
not_self_contained_list = getNotSelfContainCases(current_class)
not_len = len(not_self_contained_list)
#print(class_name)
#print(not_self_contained_list)
has_default = True
if(case_nums == 0):
print class_name
if(not_len / case_nums > 0.8):
has_default = False
if has_default == False:
res += "\tGENERATESTART(%d)\n\n" %(case_nums)
else:
res += "\tGENERATESTART(%d)\n\n" %(case_nums * 100)
#Handling class need specific variable like identifier
specific = is_specific(current_class.name)
if(specific[0]):
res += "\t\t%s_val_ = gen_%s();\n" % (specific[1], specific[1])
res += "\n\tGENERATEEND\n}\n\n"
return res
if(has_switch):
res += "\tSWITCHSTART\n"
case_id = 0
#for each_case in current_class.caseList:
for i in range(len(current_class.caseList)):
if(has_switch):
res += "\t\tCASESTART(" + str(case_id) + ")\n"
case_id += 1
res += genGenerateOneCase(current_class, i)
if(has_switch):
res += "\t\tCASEEND\n"
#if(has_switch):
# res += "\tSWITCHEND\n"
tmplate_str = """
default:{
int tmp_case_idx = rand() %% %d;
switch(tmp_case_idx){
%s
}
}
}
"""
if(has_switch and has_default == False):
res += "\tSWITCHEND\n"
elif(has_default):
tmp_str = ""
for i in range(not_len):
tmp_str += "CASESTART(" + str(i) + ")\n"
tmp_str += genGenerateOneCase(current_class, not_self_contained_list[i])
tmp_str += "case_idx_ = %d;\n" % (not_self_contained_list[i])
tmp_str += "CASEEND\n"
res += tmplate_str % (not_len, tmp_str)
res += "\n\tGENERATEEND\n}\n\n"
return res
def genTranslateBegin(class_name):
"""
dict(): class_name --> api_dict
"""
global semanticRule
ir_handlers = semanticRule["IRHandlers"]
res = list()
for item in ir_handlers:
if item["IRType"] == class_name:
for handler in item["PreHandler"]:
res.append(handler["Function"] + "(" + ", ".join(handler["Args"]) + ");")
return "\t" + "\n\t".join(res) + "\n"
def genTranslateEnd(class_name):
"""
dict(): class_name --> api_dict
"""
res = list()
ir_handlers = semanticRule["IRHandlers"]
for item in ir_handlers:
if item["IRType"] == class_name:
for handler in item["PostHandler"]:
res.append(handler["Function"] + "(" + ", ".join(handler["Args"]) + ");")
return "\t" + "\n\t".join(res) + "\n"
def genTranslate(current_class):
"""
input:
s
output:
translate def : stirng
"""
has_switch = len(current_class.caseList) != 1
class_name = underline_to_hump(current_class.name)
res = "IR* " + class_name + "::translate(vector<IR *> &v_ir_collector){\n"
res += "\tTRANSLATESTART\n\n"
res += genTranslateBegin(current_class.name)
#Handling class need specific variable like identifier
specific = is_specific(current_class.name)
if(specific[0]):
if "iteral" in class_name and specific[1] == 'string':
res += "\t\tres = new IR(k" + current_class.name + ", " + specific[1] + "_val_, data_type_, scope_, data_flag_);\n"
else:
res += "\t\tres = new IR(k" + current_class.name + ", " + specific[1] + "_val_, data_type_, scope_, data_flag_);\n"
res += genTranslateEnd(current_class.name)
res += "\n\tTRANSLATEEND\n}\n\n"
return res
if(has_switch):
res += "\tSWITCHSTART\n"
case_id = 0
#for each_case in current_class.caseList:
for i in range(len(current_class.caseList)):
#each_case = current_class.caseList[i]
if(has_switch):
res += "\t\tCASESTART(" + str(case_id) + ")\n"
case_id += 1
res += transalteOneCase(current_class, i)
if(has_switch):
res += "\t\tCASEEND\n"
if(has_switch):
res += "\tSWITCHEND\n"
res += genTranslateEnd(current_class.name)
res += "\n\tTRANSLATEEND\n}\n\n"
return res
def genDataTypeEnum():
res = "enum DATATYPE{"
res += """
#define DECLARE_TYPE(v) \\
k##v,
ALLDATATYPE(DECLARE_TYPE)
#undef DECLARE_TYPE
"""
res += "};\n"
return res
def genClassTypeEnum():
res = "enum NODETYPE{"
res += """
#define DECLARE_TYPE(v) \\
v,
ALLTYPE(DECLARE_TYPE)
#undef DECLARE_TYPE
"""
res += "};\n"
res += "typedef NODETYPE IRTYPE;\n"
return res
def genClassDeclaration(class_list):
res = ""
res += """
#define DECLARE_CLASS(v) \\
class v ; \
ALLCLASS(DECLARE_CLASS);
#undef DECLARE_CLASS
"""
return res
def genTokenForOneKeyword(keyword, token):
return "%s\tTOKEN(%s)\n" % (keyword, token)
def genParserUtilsHeader(token_dict):
with open(configuration.parser_utils_header_template_path, 'r') as f:
content = f.read()
replaced = ""
for i in token_dict.values():
replaced += "TOKEN_%s, \n" % i.token_name
content = content.replace("__TOKEN_STATE__", replaced)
return content
def genFlex(token_dict):
res = ""
res += configuration.gen_flex_definition()
res += "\n"
res += configuration.gen_flex_options()
res += "\n"
res += "%%\n"
extra_rules_path = "./data/extra_flex_rule"
if args.extraflex:
extra_rules_path = args.extraflex
contents = ""
with open(extra_rules_path, 'rb') as f:
contents = f.read()
ban_ptn = re.compile(r"PREFIX_([A-Z_]*)")
ban_res = ban_ptn.findall(contents)
ban_list = set(ban_res)
if(len(contents) > 2 and contents[-1] != '\n'):
contents += '\n'
contents = contents.split("+++++\n")
contents = [i.split("-----\n") for i in contents]
#print(contents)
test = ""
for i in contents:
if(len(i) < 2):
continue
if len(i[1]) > 0 and i[1][0] == '[':
## Update match string here
tmpp = copy.deepcopy(i)
token_list = tmpp[1].split("\n")[0]
i[1] = "\n".join(tmpp[1].split("\n")[1:])
token_list = token_list[1:-1].split(", ")
for dd in token_list:
for token in token_dict.values():
if dd == token.token_name:
if token.match_string != tmpp[0].strip():
token.match_string = tmpp[0].strip()
token.is_keyword = False
break
#print(token_list)
test += "%s {\n\t%s}\n" % (i[0].strip(), "\n\t".join(i[1].replace("PREFIX_", configuration.token_prefix).split("\n")))
#print(test)
#raw_input()
test += "\n"
#print(test)
#print(token_dict)
for token in token_dict.values():
#print(token.token_name)
if(token.token_name in ban_list):
continue
res += genTokenForOneKeyword(token.match_string, token.token_name)
res += test
res += "%%\n"
return res
def genBisonType(class_set):
"""
input:
set of GenClass : set
Output:
"%type <import_statement_t> import_statement\nxxxx": string
"""
res = ""
for c in class_set:
cname = c.name
underline_name = hump_to_underline(cname)
res += "%%type <%s_t>\t%s\n" % (underline_name, underline_name)
return res
def genBisonPrec(token_dict):
"""
input:
token_dict: dict
output:
"%right xxx yyy": string
"""
precdict = dict()
for token_name, token in token_dict.items():
if token.prec != 0:
if(precdict.has_key(token.prec) == False):
precdict[token.prec] = []
precdict[token.prec].append(token_name)
res = ""
for (key, value) in precdict.items():
tmp = ""
tmp_name = ""
for token_name in value:
tmp += " %s" % token_name
res += "%%%s %s\n" % (token_dict[value[0]].assoc, tmp)
return res
def genBisonToken(token_dict):
"""
input:
token_dict: dict
output:
"%token xxx yyy": string
"""
counter = 0
token_res = ""
type_token = ""
for token_name in token_dict.keys():
if(token_dict[token_name].ttype != "0"):
type_token += "\n%%token <%s> %s\n" % (token_dict[token_name].ttype, token_name)
continue
if counter % 8 == 0:
token_res += "\n%token"
token_res += " " + token_name
counter += 1
token_res += type_token
token_res += "\n"
# This is hardcoded. To fix
if "php" in args.input:
token_res += "%token OP_DOLLAR PREC_ARROW_FUNCTION\n"
token_res += "%token <sval> T_VARIABLE T_STRING_VARNAME\n"
return token_res
def genBisonDataType(extra_data_type, allClass):
res = ""
for k, v in extra_data_type.items():
res += "\t%s\t%s;\n" % (v, k)
for c in allClass:
underline_name = hump_to_underline(c.name)
res += "\t%s\t%s;\n" % (c.name+" *", underline_name+"_t")
return res