forked from amespi22/code_rewrite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_expand.py
executable file
·1333 lines (1240 loc) · 50.9 KB
/
code_expand.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 python3
from antlr_funcs import *
import argparse
import sys
import itertools
import subprocess
import re
def main():
#read in the function and file we weant to look at
parser = argparse.ArgumentParser()
parser.add_argument("--only-new-vars", dest="only_new_vars",
help="Specify that only variables generated by the code expansion are the LHS variables for repair ingredients",
action='store_true', required=False, default=False)
parser.add_argument("-n", "--file_name", help="Input file to look at",
type=str, required=True)
parser.add_argument("-f", "--out_file", help="Output file name",
type=str, required=False, default="new_code_expand.c")
parser.add_argument("-p", "--pre_process", help="File with list of files for pre-processing.\
File names must be absolute. Only one file name per line.",
type=str, required=False, default="")
args = parser.parse_args()
prog_name = args.file_name
out_name = args.out_file
pre_process = args.pre_process
#this global things feels really wrong, but it keeps me from breaking the
#way things are called in the loop at the bottom of the function
global funcs_and_args
#functions and their return types
global funcs_and_rts
global macros
dont_eval=[]
okay_to_eval=[]
okay_ = ["sizeof"]
global struct_ptrs
global keywords
global defines
keywords=None
defines=None
if pre_process != "":
#This means we have a file to parse
#File should have a new line for each file to parse
#Files named should be .c files
print("Starting pre-processing")
funcs_and_args,funcs_and_rts,macros,dont_eval,okay_to_eval,struct_ptrs,keywords,defines = get_json_data(pre_process,infile=prog_name)
print("Pre-processing done")
else:
funcs_and_rts = {}
funcs_and_args = {}
struct_ptrs = {}
macros = None
for x in okay_:
if x not in okay_to_eval:
okay_to_eval.append(x)
_pp_prog_name=f"{prog_name}.pp"
macros=preprocess(macros,prog_name,_pp_prog_name)
#if not(macros == False):
# _pp_prog_name=f"{prog_name}.pp"
# macros=preprocess(macros,prog_name,_pp_prog_name)
#else:
# macros=preprocess(None,prog_name,f"{prog_name}.pp")
# _pp_prog_name=f"{prog_name}"
from os import path as path
fix_ingred_fileid=path.splitext(path.basename(f"{prog_name}"))[0]
bl_filename=f"fn_blacklist.{fix_ingred_fileid}.txt"
fix_ingred_id=re.sub(r'-',r'_',fix_ingred_fileid)
#original program
cur_pro = ""
with open(_pp_prog_name, 'r') as infile:
cur_pro = infile.read()
#get the dictionary that maps line numbers with the re-write
p,t = get_tree_from_file(_pp_prog_name)
print_ctx_bfs(t,"original_tree")
d1 = get_all_decs(t) if args.only_new_vars else []
#loop to run all code transformations
#order matters, don't re-arrange
change_funcs = [expand_case, expand_conditionals,expand_blockItems, if_else_break, insert_loop_braces, expand_if_else, expand_sizeof, single_declarations, expand_decs,expand_func_args]
apply_changes = [gen_case, gen_conditionals, gen_blockItems, gen_if_else_break, gen_loop_braces, gen_if_changes, gen_expand_changes, gen_dec_changes, gen_dec_changes,gen_func_changes]
j = 0
i = 0
f_n = 0
print("Starting Transformations")
while i < len(change_funcs):
"""
if i != 0:
p,t = get_tree_from_string(cur_pro)
rewrite = change_funcs[i](t)
cur_pro = apply_changes[i](cur_pro, rewrite)
"""
again = True
if i == len(change_funcs)-1:
break
while again:
print(f"Start {change_funcs[i].__name__} pass")
old_pro = cur_pro
if j != 0:
p,t = get_tree_from_string(cur_pro)
rewrite = change_funcs[i](t)
cur_pro = apply_changes[i](cur_pro, rewrite)
print("End pass")
#print_inter_file(f_n, cur_pro)
#print_ctx_bfs(t,f"help_pre_{f_n}")
f_n += 1
if i == len(change_funcs)-2:
print(f"Start {change_funcs[i+1].__name__} pass")
p,t = get_tree_from_string(cur_pro)
rewrite = change_funcs[i+1](t)
cur_pro = apply_changes[i+1](cur_pro, rewrite)
print("End pass")
#print_inter_file(f_n, cur_pro)
f_n += 1
j += 1
again = not(old_pro == cur_pro) and i == len(change_funcs)-2
#print(again)
i += 1
print("all done with passes")
#FIX-INGREDIENTS
write_new_program(cur_pro, f"{out_name}.prev")
p,t = get_tree_from_string(cur_pro)
d2 = get_all_decs(t)
#dictionary where:
# key = function_name //use get_func_name() on a function definition context
# value = [new_declaration_nodes] // only declarations introducted by the code in this program
new_decs = get_dec_diffs(d1,d2) if args.only_new_vars else d2
for i,k in enumerate(new_decs.keys()):
nd="\n - "+"\n - ".join([get_string2(n) for n in new_decs[k]])
print(f"{i} : [{k}] {type(new_decs[k])} [{'new' if args.only_new_vars else 'all'} function decls] {nd}")
print_ctx_bfs(t,"help")
printer=ScopeListener()
printer.set_functions(dont_eval+okay_to_eval)
walker = ParseTreeWalker()
walker.walk(printer,t)
scope_vars = get_function_info(functions=get_functions(t),fscope=printer.scopes,dont_eval=dont_eval)
#fix_loc_rewrites = get_fix_loc_rewrites(scope_vars)
fix_loc_rewrites,new_funcs = get_fix_loc_subfns(scope_vars,new_decs,okay_to_eval,id_=fix_ingred_id,root=t,ptr_t=struct_ptrs,defines=defines)
cur_pro = gen_fix_loc_changes(cur_pro, fix_loc_rewrites)
#write out the new program
print(f"Writing output file {out_name}")
write_new_program(cur_pro, out_name)
with open(bl_filename,"w") as o:
for i in new_funcs:
o.write(f"{i}\n")
o.close()
def print_inter_file(i, cur_pro):
with open(f"tmp{i}.c", 'w') as out_f:
print(f"Writing file {i}")
out_f.write(cur_pro)
def expand_blockItems(ctx):
#get all block items that end in ;
bic = "<class 'CParser.CParser.BlockItemContext'>"
fns = get_functions(ctx)
rewrites = []
for f in fns:
bics = find_ctx(f, bic)
r_bics = [x for x in bics if x.getText().endswith(";")]
for r in r_bics:
#rewrites will be end locations
rewrites.append(get_end_loc(r))
return rewrites
def gen_blockItems(cur_prog, rewrite):
lns = cur_prog.split('\n')
line_deltas = {}
for r in rewrite:
er, ec = r
#print(f"len = {len(lns[er-1])} row = {ec},{lns[er-1][ec]} line = {lns[er-1]}")
if len(lns[er-1])-1 != ec:
ln = lns[er-1]
#print(f"{ln[:ec+1]}\n{ln[ec:]}")
if er - 1 in line_deltas:
d = line_deltas[er-1]
lns[er-1] =f"{ln[:ec+1+d]}\n{ln[ec+d:]}"
line_deltas[er-1] += 1
else:
lns[er-1] =f"{ln[:ec+1]}\n{ln[ec:]}"
line_deltas[er-1] = 1
return "\n".join(lns)
def expand_case(ctx):
#insert '{' after each "case():"
#insert '}' at end of switch
sw = "<class 'CParser.CParser.SelectionStatementContext'>"
lsc = "<class 'CParser.CParser.LabeledStatementContext'>"
fns = get_functions(ctx)
rewrites = []
for f in fns:
switches = find_ctx(f, sw)
#get rid of the if statements
s = [x for x in switches if x.getChild(0).getText() == 'switch']
for w in s:
#get all the Labled StatementContexts
cs = find_ctx(w, lsc)
for c in cs:
#append the start and end location of the
#case so we can and curles at the re-write
#the place right after the colon
if c.getChild(0).getText() == 'case':
sl = get_start_loc(c.getChild(3))
#the place at the end
el = get_end_loc(c.getChild(3))
if c.getChild(0).getText() == 'default':
sl = get_start_loc(c.getChild(2))
#the place at the end
el = get_end_loc(c.getChild(2))
rewrites.append((sl,el))
return rewrites
def gen_case(cur_prog, rewrite):
lns = cur_prog.split('\n')
bc = '{'
ec = '}'
deltas = {}
for r in rewrite:
(sr,sc),(er,ec) = r
#add open curly to case
if sr-1 not in deltas:
deltas[sr-1] = 1
d = 0
else:
deltas[sr-1] += 1
d = deltas[sr-1] - 1
ln = lns[sr-1]
lns[sr-1] = f"{ln[:sc-1+d]}{{{ln[sc-1+d:]}"
#add end curly to end
#first see if we have anything changed by the addition of
#the curly brace from above
if er-1 in deltas:
d = deltas[er-1]
else:
d = 0
ln = lns[er-1]
lns[er-1] = f"{ln[:ec+1+d]}}}{ln[ec+1+d:]}"
return "\n".join(lns)
def insert_loop_braces(ctx):
#get all functions
loop_stmt = "<class 'CParser.CParser.IterationStatementContext'>"
if_stmt = "<class 'CParser.CParser.SelectionStatementContext'>"
fns = get_functions(ctx)
rewrites = []
#for else conditions we will want to check the 5th child of SelectionStatementContext
#and do the same thing
for f in fns:
loops = find_ctx(f, loop_stmt)
ifs = find_ctx(f, if_stmt)
loops.extend(ifs)
#get all loops in functions
for l in loops:
if l.getText().startswith("do"):
continue
#check to see if there are curly braces
l_body = l.getChild(4)
if not l_body:
pass
elif l_body.getText().startswith("{"):
pass
else:
#add if necessary
rewrites.append((get_start_loc(l_body),get_end_loc(l_body)))
if l.getChildCount() == 7:
#we have if...else
l_body = l.getChild(6)
if l_body.getText().startswith("{"):
continue
else:
rewrites.append((get_start_loc(l_body),get_end_loc(l_body)))
return rewrites
def expand_conditionals(ctx):
#get the conditional statement
if_stmt = "<class 'CParser.CParser.SelectionStatementContext'>"
fns = get_functions(ctx)
rewrites = []
for f in fns:
ifs = find_ctx(f, if_stmt)
for l in ifs:
if not l.getChild(4).getText().startswith('{'):
#add in the curly brace to start and end of IF
rewrites.append((get_start_loc(l.getChild(4)),get_end_loc(l.getChild(4))))
if l.getChildCount() != 7:
continue
if not l.getChild(6).getText().startswith('{'):
rewrites.append((get_start_loc(l.getChild(6)),get_end_loc(l.getChild(6))))
#add in the curly brace to start and end of ELSE
#find the body
#wewrite it the whole thing to not suck
#profit
return rewrites
def gen_conditionals(cur_prog, rewrite):
lns = cur_prog.split('\n')
i = 0
for r in rewrite:
s,e = r
#may want to do this with a line delta but I'll test this first
if s[0] == e[0]:
#start and end are on the same line and need to add 1 to the index for the end
#start curly
d = calc_delta_conditionals(rewrite[:i],s)
ln = lns[s[0]-1]
lns[s[0]-1] = f"{ln[:s[1]-1+d]}{{{ln[s[1]-1+d:]}"
d = calc_delta_conditionals(rewrite[:i],e)
ln = lns[e[0]-1]
lns[s[0]-1] = f"{ln[:e[1]+2+d]}}}{ln[e[1]+2+d:]}"
else:
d = calc_delta_conditionals(rewrite[:i],s)
ln = lns[s[0]-1]
lns[s[0]-1] = f"{ln[:s[1]-1+d]}{{{ln[s[1]-1+d:]}"
ln = lns[e[0]-1]
d = calc_delta_conditionals(rewrite[:i],e)
lns[e[0]-1] = f"{ln[:e[1]+1+d]}}}{ln[e[1]+1+d:]}"
#start and end are on different lines and don't need to add 1 to the index
i += 1
ret = "\n".join(lns)
of = open('tmp_fmt', 'w')
of.write(ret)
of.close()
s,o = subprocess.getstatusoutput(f"indent -kr -st -l300 tmp_fmt 2>/dev/null")
return o
#return ret
def calc_delta_conditionals(before, cur):
ret = 0
for b in before:
s,e = b
#cur[0] = line
#cur[0] = column in line
if cur[0] == s[0]:
#this means they are the same line
if cur[1] > s[1]:
ret += 1
if cur[0] == e[0]:
if cur[1] > e[1]:
ret += 1
return ret
def if_else_break(ctx):
if_stmt = "<class 'CParser.CParser.SelectionStatementContext'>"
fns = get_functions(ctx)
rewrites = []
for f in fns:
ifs = find_ctx(f, if_stmt)
for l in ifs:
if l.getChildCount() == 7:
#we have if...else
l_body = l.getChild(6)
if l_body.getText().startswith("{"):
continue
else:
#check to see if the if and the else are on the same line
if_start = get_start_loc(l.getChild(0))
else_start = get_start_loc(l.getChild(5))
else_stmt_start = get_start_loc(l_body)
else_stmt_end = get_end_loc(l_body)
if if_start[0] != else_start[0]:
continue
if else_stmt_start[0] == else_start[0]:
#both are on the same line and we need a newline between them
rewrites.append((else_stmt_start,else_stmt_end))
return rewrites
def gen_if_else_break(cur_prog, rewrites):
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns]
for b,e in rewrites:
l = lns[b[0]-1]
es = b[1]
lns[b[0]-1] = f"{l[:es-1]}\n{{\n{l[es-1:]}"
l = lns[e[0]-1]
ee = e[1]
lns[e[0]-1] = f"{l[:ee+1]}\n}}{l[ee+1:]}"
return "".join(lns)
def gen_loop_braces(cur_prog, rewrite):
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns]
for b,e in rewrite:
#print("1" + lns[b[0]-1])
spaces = get_line_spaces(lns[b[0]-2])
lns[b[0]-1] = f"{spaces}{{\n{lns[b[0]-1]}"
#print("2" + lns[e[0]-1])
lns[e[0]-1] = f"{lns[e[0]-1]}{spaces}}}\n"
return "".join(lns)
def gen_fix_loc_changes(cur_prog, rewrite):
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns]
lns = lns[:-1]
for r in rewrite:
code, loc = r
spaces = get_line_spaces(lns[loc[0]-2])
lns[loc[0]-2] += f"{spaces}{code.strip()}\n"
return "".join(lns)
def expand_if_else(ctx):
sel_stmt = "<class 'CParser.CParser.SelectionStatementContext'>"
fns = get_functions(ctx)
rewrites = {}
#This gives us all functions in the file and it's args
for f in fns:
funcs_and_rts[get_func_name(f)] = f.getChild(0).getText()
#fix case where there is no return type of a functino
for key,value in funcs_and_rts.items():
if value.startswith(f"{key}("):
funcs_and_rts[key] = 'int'
#for all functions
for f in fns:
ifs = find_ctx(f, sel_stmt)
ifs = [x for x in ifs if not ("&&" in x.getText() and "==" in x.getText())]
all_types, all_vars = get_all_vars(f,True)
#for all if statements
for i in ifs:
fcs = get_function_calls(i.getChild(2))
#print([f.getText() for f in fcs])
z = itertools.permutations(fcs,2)
for zz in z:
if is_descendant(zz[0],zz[1]):
if zz[0] in fcs:
fcs.remove(zz[0])
#print([f.getText() for f in fcs])
#print("get_functions")
#print([f for f in funcs_and_rts.keys()])
#all function calls inside the if
for c in fcs:
f_name = c.getChild(0).getText()
if f_name in funcs_and_rts:
func_args = c.getChild(2).getText()
r_vars = gen_new_vars(all_vars, 1)
all_vars.extend(r_vars)
start_loc = get_start_loc(c)
end_loc = get_end_loc(c)
dec = r_vars[0]
pctx = get_top_dec_parent(i)
func_loc = get_start_loc(pctx)
rewrites[start_loc, end_loc] = (f"{fix_type(funcs_and_rts[f_name])} {dec} = {c.getText()};", dec, func_loc)
#rewrites[start_loc, end_loc] = (f"{funcs_and_rts[f_name]} {dec} = {c.getText()};", dec)
return rewrites
def expand_sizeof(ctx):
sel_stmt = []
sel_stmt.append("<class 'CParser.CParser.SelectionStatementContext'>")
sel_stmt.append("<class 'CParser.CParser.IterationStatementContext'>")
sel_stmt2 = "<class 'CParser.CParser.ShiftExpressionContext'>"
fns = get_functions(ctx)
rewrites = {}
dec = "unsigned long "
#go through all the functions
for f in fns:
c_vars = set()
loops_selections = find_ctx_list(f, sel_stmt)
# for all loops and conditionals
for l in loops_selections:
if l.getText().startswith("do"):
continue
#this is just the stuff between parens in the statement l.getChild(2)
sizes = find_ctx(l.getChild(2), sel_stmt2)
#for all the sizeof() statements get the re-write information
size = [x for x in sizes if x.getText().startswith('sizeof(')]
#get a new variable for every sizeof in the statement
vs = [f"tlv_size_{x}" for x in range(len(size))]
i = 0
for s in size:
start_loc = get_start_loc(s)
end_loc = get_end_loc(s)
if vs[i] in c_vars:
rewrites[start_loc, end_loc] = (f"{vs[i]}= {s.getText()};", f"{vs[i]}")
else:
rewrites[start_loc, end_loc] = (f"{dec}{vs[i]}= {s.getText()};", f"{vs[i]}")
c_vars.add(vs[i])
i += 1
return rewrites
def gen_if_changes(cur_prog, rewrite):
lns = cur_prog.split('\n')
lns = [f"{x}\n" for x in lns]
lns = lns[:-1]
diff = 0
prev_line = 0
for key,val in rewrite.items():
start_loc, end_loc = key
func_call,var_use,p_loc = val
#if the start and end loc lines are the same
if key[0][0] == key[1][0]:
if prev_line != start_loc[0]:
diff = 0
ln = lns[start_loc[0]-1]
start = ln[:start_loc[1]-1-diff]
end = ln[end_loc[1]+1-diff:]
middle = var_use
pre_len = len(ln)
spaces = get_line_spaces(ln)
line_change = f"{start}{middle}{end}"
diff = pre_len - len(line_change) + diff
lns[start_loc[0]-1] = f"{line_change}"
lns[p_loc[0]-2] += f"{spaces}{func_call}\n"
prev_line = start_loc[0]
#if multi-line we need to compress the functioncall line to 1
else:
print("You should really have done this")
return "".join(lns)
def gen_expand_changes(cur_prog, rewrite):
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns]
lns = lns[:-1]
diff = 0
prev_line = 0
keys = list(rewrite.keys())
keys.sort()
for key in keys:
start_loc, end_loc = key
func_call,var_use = rewrite[key]
#if the start and end loc lines are the same
if key[0][0] == key[1][0]:
if prev_line != start_loc[0]:
diff = 0
ln = lns[start_loc[0]-1]
start = ln[:start_loc[1]-1-diff]
end = ln[end_loc[1]+1-diff:]
middle = var_use
pre_len = len(ln)
spaces = get_line_spaces(ln)
line_change = f"{start}{middle}{end}"
diff = pre_len - len(line_change)
lns[start_loc[0]-1] = f"{line_change}"
lns[start_loc[0]-2] += f"{spaces}{func_call}\n"
prev_line = start_loc[0]
#if multi-line we need to compress the functioncall line to 1
else:
print("You should really have done this")
return "".join(lns)
def expand_func_args(ctx):
loop_stmt = "<class 'CParser.CParser.IterationStatementContext'>"
loops = find_ctx(ctx, loop_stmt)
if_stmt = "<class 'CParser.CParser.SelectionStatementContext'>"
ifcons = find_ctx(ctx, if_stmt)
jump_stmt = "<class 'CParser.CParser.JumpStatementContext'>"
jumps = find_ctx(ctx, jump_stmt)
whiles = [x for x in loops if ('for' in x.getChild(0).getText() or 'while' in x.getChild(0).getText())]
ifcons = [x.getChild(2) for x in ifcons if 'if' in x.getChild(0).getText() ]
#make sure we are not messing with the contents of a return statement
rets = [x for x in jumps if 'return' in x.getChild(0).getText()]
lps = [x.getChild(2) for x in whiles]
#find all functions, record their names and paramaters
fns = get_functions(ctx)
rewrites = {}
start_locs = {}
tmp = {}
for k,v in struct_ptrs.items():
tmp[v] = k
#This gives us all functions in the file and its args
for f in fns:
args = []
fn_args = get_func_args(f)
for i,j in fn_args:
if i in tmp:
args.append((f"{tmp[i]}*",j))
if '[' in j:
args.append((f"{i}*",j))
else:
args.append((i,j))
funcs_and_args[get_func_name(f)] = args
#for each function find all <class 'CParser.CParser.PostfixExpressionContext'>
for f in fns:
skip = False
new_vars = []
all_types, all_vars = get_all_vars(f,True)
pecs = find_ctx(f, "<class 'CParser.CParser.PostfixExpressionContext'>")
pecs = [p for p in pecs if p.getChildCount() > 1 and p.getChild(0).getText() in funcs_and_args]
pecs = remove_inner_funcs(pecs)
#print([p.getChild(0).getText() for p in pecs])
try:
for p in pecs:
#make sure we don't do anything with things inside the conditional check
#of the while or for loop
for l in lps + ifcons + rets:
if is_descendant(p, l):
skip = True
if skip:
skip = False
continue
f_name = p.getChild(0).getText()
#print(f"function {f_name} is present with args {p.getChild(2).getText()}")
#print(f"child count {p.getChildCount()}")
func_args = parse_func_call_args(p)
func_arg_names = [get_string2(x) for x in func_args]
if func_arg_names == [')']:
continue
#replace index in function arguments
rep = []
j = 0
#Find indexes to replace.
#I do this in two passes so I can create
#all the new variables in one shot
#print(all_vars)
#should do this better but without going global this works
all_vars = [a for a in all_vars if a.startswith("tlv")]
for i in func_arg_names:
#if i not in all_vars and has_func(func_args[j]):
if i not in all_vars:
rep.append(j)
j += 1
# only here if we have 1 or more arguments to pull out
if len(rep) > 0:
#get new variables to use
start_loc = get_start_loc(p)
#sometimes we are in a situation like func(a) + func(b)
#and a needs to be tlv1 and b tlv2
if start_loc[0] in start_locs:
start_locs[start_loc[0]] = start_locs[start_loc[0]] + 1
else:
start_locs[start_loc[0]] = 0
r_vars = gen_new_vars(new_vars + all_vars, len(rep)+start_locs[start_loc[0]])
r_vars.reverse()
end_loc = get_end_loc(p)
#print(f"start location {start_loc} end location = {end_loc}")
#add to the list of all variables so they are not used
#again in the same function on another call
#all_vars.extend(r_vars)
fun_arg_types = funcs_and_args[f_name]
#print(f"{f_name} has types {fun_arg_types}")
#added this cause we don't need functions that take
#const args to make the varialbes we send them const
de_const(fun_arg_types)
#This happens in nested situations and for now
#I ignore it silently
if len(func_args) > len(fun_arg_types):
#print(f"messed up here with {p.getText()}")
continue
new_arg_string = f"{f_name}("
new_var_dec = ""
for i in range(len(func_args)):
if i in rep:
#replace that variable
v = r_vars.pop()
new_var_dec += f"{fun_arg_types[i][0]} {v} = {func_arg_names[i]};\n"
new_vars.append(v)
new_arg_string += f"{v},"
#print(f"{fun_arg_types[i][0]} {v} = {func_arg_names[i]};\n")
else:
#use what was already there
new_arg_string += f"{func_arg_names[i]},"
rewrites[start_loc,end_loc] = (new_var_dec,new_arg_string[:-1]+')')
except Exception as e:
print(f"messed up here with {p.getText()}")
print(e)
continue
#record the changes needed to re-write the code
return rewrites
def has_func(ctx):
nums = find_ctx(ctx,"<class 'CParser.CParser.PostfixExpressionContext'>")
if len(nums) == 1:
return True
return False
def remove_inner_funcs(ctx_list):
ret_list = ctx_list
for c in ctx_list:
inner = find_ctx(c, "<class 'CParser.CParser.PostfixExpressionContext'>")
for i in inner:
if i in ctx_list:
ret_list.remove(i)
return ret_list
def gen_func_changes(cur_prog, rewrite):
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns]
lns = lns[:-1]
tab = chr(32) * 4
line_deltas = {}
#of = open("tmp_ln_prints", 'a')
keys = list(rewrite.keys())
keys.sort()
for key in keys:
start_loc, end_loc = key
val = rewrite[key]
var_decs,func_call = val
#if the start and end loc lines are the same
if key[0][0] == key[1][0]:
if key[0][0] not in line_deltas:
ln = lns[start_loc[0]-1]
start = ln[:start_loc[1]-1]
end = ln[end_loc[1]+1:]
middle = val[1]
spaces = get_line_spaces(ln)
var_decs = indent_by_newline(var_decs, spaces, tab)
line_change = f"{tab}{start}{middle}{end}"
line_deltas[key[0][0]] = len(line_change) - len(lns[start_loc[0]-1])
#of.write(lns[start_loc[0]-1])
lns[start_loc[0]-1] = f"{spaces}{{\n{var_decs}{line_change}{spaces}}}\n"
#of.write(f"{spaces}{{\n{var_decs}{line_change}{spaces}}}\n")
else:
orig_len = len(lns[start_loc[0]-1]) + line_deltas[key[0][0]]
s_lns = lns[start_loc[0]-1].split('\n')
ln = s_lns[len(s_lns)-3]
spaces = get_line_spaces(s_lns[1])
var_decs = indent_by_newline(var_decs, spaces,' ')
delta = line_deltas[key[0][0]]
start = ln[:start_loc[1]-1 + delta]
end = ln[end_loc[1]+1+delta:]
middle = val[1]
spaces = get_line_spaces(ln)
line_change = f"{start}{middle}{end}"
#of.write(line_change)
# add var decs to s_lns
s_lns[len(s_lns)-3] = line_change
s_lns[1] = f"{var_decs}{s_lns[1]}"
# add line change to s_lns
line_deltas[key[0][0]] = len(line_change) - orig_len
lns[start_loc[0]-1] = "\n".join(s_lns)
#if multi-line we need to compress the functioncall line to 1
else:
s = start_loc[0]-1
e = end_loc[0]-1
middle = val[1]
ln = lns[start_loc[0]-1]
start = ln[:start_loc[1]-1]
spaces = get_line_spaces(ln)
var_decs = indent_by_newline(var_decs, spaces, tab)
ln = lns[end_loc[0]-1]
end = ln[end_loc[1]+1:]
for i in range(s+1,e):
#remove the newlines if multi-line function call
lns[i] = ""
#kill the last line since it's now part of variable "end"
lns[e] = ""
#of.write(lns[s])
#of.write(f"{spaces}{{\n{var_decs}{tab}{start}{middle}{end}{spaces}}}\n")
lns[s] = f"{spaces}{{\n{var_decs}{tab}{start}{middle}{end}{spaces}}}\n"
#of.close()
#exit()
return "".join(lns)
#Used for getting the edited/new lines in aligned with surrounding text
def get_line_spaces(ln):
spaces = len(ln) - len(ln.strip()) - 1
return chr(32) * spaces
def indent_by_newline(lns, spcs, tab):
lns = lns.split('\n')
lns = lns[:-1]
rt = ""
for l in lns:
rt += tab + spcs + l + "\n"
return rt
def gen_new_vars(old_vars,num):
#base for a temporary local variable
base = "tlv"
i = 1
rv = []
while True:
nv = f"{base}{i}"
if nv not in old_vars:
rv.append(nv)
if len(rv) == num:
#flip these so that when I pop them they appear in order
rv.reverse()
return rv
i += 1
#This is for when you have multiple declarations on one line and at leaset
#of of them get initialized
def single_declarations(ctx):
rewrite = {}
decs = find_ctx(ctx, "<class 'CParser.CParser.DeclarationContext'>")
for d in decs:
#see which declarations are "compound"
cmpd = find_ctx(d, "<class 'CParser.CParser.InitDeclaratorContext'>")
if cmpd == [] :
#print("No initializer+declarations found")
pass
else:
#figure out the arguments.
try:
cc = d.getChild(1).getChildCount()
if cc > 1:
#we are with more than one declaration and one is initialized
typ = d.getChild(0).getText()
typ = fix_type(typ)
all_vars_o = [d.getChild(1).getChild(x).getText() for x in range(cc) if d.getChild(1).getChild(x).getText() != ',']
all_vars = []
for a in all_vars_o:
if '(' in a:
nv = fix_type(a[:a.rfind(')')]) + a[a.rfind(')'):]
all_vars.append(nv)
else:
all_vars.append(a)
else:
#if here we don't have more than one variable in the
#declaration and expand_decs will get it
continue
if '*' in typ:
all_vars[0] = f"{typ[typ.find('*'):]}{all_vars[0]}"
typ = typ[:typ.find('*')]
rs = ""
"""
if len(all_vars) > 1:
#we need to see if the type ends with a *
#if so, remove the * and place it on the first var
if typ.endswith("*"):
all_vars[0] = f"*{all_vars[0]}"
typ = typ[:-1]
"""
for a in all_vars:
rs+= f"{typ} {a};\n"
#line_num - 1 cause I think it's not 0 indexed
rewrite[(get_line_num(d)-1,get_last_line_num(d))] = rs
except:
continue
return rewrite
#expand any declarations and initilizations that are together
#Input program name
#Outpue dictionary of edits "dict[fistline,lastline] = edit"
#limiting to declarations in functions.
def expand_decs(ctx):
rewrite = {}
fns = get_functions(ctx)
for f in fns:
decs = find_ctx(f, "<class 'CParser.CParser.DeclarationContext'>")
for d in decs:
#see which declarations are "compound"
cmpd = find_ctx(d, "<class 'CParser.CParser.InitDeclaratorContext'>")
if (cmpd == []) or ('=' not in d.getText()):
pass
#print("No initializer+declarations found")
else:
if ("const" in d.getChild(0).getText() or "char*" in d.getChild(0).getText()):
#Here if we have a const that can't be broken up
typ = d.getChild(0).getText()
stmt = d.getChild(1).getText()
typ = fix_type(typ)
lhs = get_string2(d.getChild(1).getChild(0).getChild(0))
rhs = get_string2(d.getChild(1).getChild(0).getChild(2))
if rhs.startswith("("):
#fix this later to get everything between () then remake rhs
rhs = fix_type(rhs)
#print(f"typ={typ},stmt={stmt},lhs={lhs},rhs={rhs}")
#This is to make sure we don't have a char array on the rhs
#if so we need to make sure to hit the else.
ts = [x[:x.find('[')] for x in get_all_vars(f, False) if '[' in x]
#First if is for char*'s that are in the code and I shouldn't minipulate
if "char*" in typ and "const" not in typ and not rhs.startswith('"'):
rewrite[(get_line_num(d)-1,get_last_line_num(d))] = f"{typ} {lhs};\n {lhs} = {rhs};\n"
else:
if "char*" in typ and rhs not in ts and rhs.startswith('"'):
rewrite[(get_line_num(d)-1,get_last_line_num(d))] = f"{typ.replace('char*','char')} {lhs}[] = {rhs};\n"
#print(f"if:{typ.replace('char*','char')} {lhs}[] = {rhs};\n")
#print(f"{d.getText()}")
else:
#this is an attempt to pass lines that I should not need to chage
#example instantiating function pointers
rewrite[(get_line_num(d)-1,get_last_line_num(d))] = f"{typ} {lhs} = {rhs};\n"
#print(f"{typ} {lhs} = {rhs};\n")
else:
#figure out the arguments.
try:
typ = d.getChild(0).getText()
stmt = d.getChild(1).getText()
var = get_string2(d.getChild(1).getChild(0).getChild(0))
rhs = get_string2(d.getChild(1).getChild(0).getChild(2))
#don't break up thigns that are setting function pointers
if rhs in funcs_and_args:
continue
#trying to fix the way getText handles structs
#rhs = fix_rhs(rhs)
typ = fix_type(typ)
if var.endswith('[ ]') or rhs.startswith('{'):
continue
#print(f"type = {typ} var = {var};")
#print(f"stmt = {stmt};")
#print(f"rhs = {rhs};")
#print(f"rewrite number {get_line_num(d)-1}")
#line_num - 1 cause I think it's not 0 indexed
rewrite[(get_line_num(d)-1,get_last_line_num(d))] = f"{typ} {var};\n{var} = {rhs};\n"
except Exception as e:
print(f"got exception {e}")
continue
return rewrite
def fix_rhs(stmt):
if '"' not in stmt and "struct" in stmt:
return fix_type(stmt)
return stmt
def gen_dec_changes(cur_prog, rewrite):
#print(cur_prog)
#print("----------")
lns = cur_prog.split('\n')
lns = [x+"\n" for x in lns[:-1]]
keys = list(rewrite.keys())
keys.sort()
for key in keys:
#key is a tuple with the first and last line that are going to be
#overwritten.
a,b = key
if lns[a].startswith("#"):
a += 1
tb = get_line_spaces(lns[a])
if a != b:
#if here we need to just rewrite the lines with nothing
for x in range(a,b):
lns[x] = ""
#this is so we can get the indentation correct
splt = rewrite[key].split('\n')
#lns[a] = f"{tb}{splt[0]}\n{tb}{splt[1]}\n"
for s in splt[:-1]:
lns[a] += f"{tb}{s}\n"
#print ("".join(lns))
return "".join(lns)
def write_new_program(p,prog_name):
#write the new file
with open(f"{prog_name}", 'w') as outfile:
outfile.write(p)
#Other type fixes should go here
#antlr seems to squish things together so if this happesn to you
#just follow the example of the const fix
def fix_type(typ):
if "extern" in typ:
typ = typ.replace("extern", "extern ")
if "const" in typ:
typ = typ.replace("const", "const ")
if "register" in typ:
typ = typ.replace("register", "register ")
if "signed" in typ:
typ = typ.replace("signed", "signed ")
if "static" in typ:
typ = typ.replace("static", "static ")
if "unsigned" in typ:
typ = typ.replace("unsigned", "unsigned ")
if "longlong" in typ:
typ = typ.replace("longlong", "long long")
if "longint" in typ:
typ = typ.replace("longint", "long int")
if "shortint" in typ:
typ = typ.replace("shortint", "short int")
if "staticint" in typ:
typ = typ.replace("staticint", "static int")
if "unsignedint" in typ:
typ = typ.replace("unsignedint", "unsigned int")
if "struct" in typ and typ.startswith("struct"):
typ = typ.replace("struct", "struct ", 1)
z = re.search(r"struct[A-Za-z0-9_]", typ)
if z:
if keywords:
srchk='|'.join(keywords)
if not re.search(r"("+srchk+r")",typ):
typ = typ.replace("struct", "struct ")
typ = typ.replace(" ", " ")
return typ
def const(dec):
"""
types = ["int", "long", "float", "double"]
for t in types:
if (t in dec) and ("const" in dec):
return True