forked from amespi22/code_rewrite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
antlr_funcs.py
executable file
·2214 lines (2054 loc) · 89.5 KB
/
antlr_funcs.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
import sys
from antlr4 import *
from CLexer import CLexer
from CParser import CParser
from CListener import CListener
from code_expand import preprocess_string
import linked_list
import inspect
import codecs
import copy
import json
import re
debug=(False,True) # [0] print debug messages ; [1] generate debug log from debug messages
gbl_debug_msg=["",0,open("debug.log","w") if debug[1] else None,debug[1] ]
#This program assumes that C.g4 has been used to create
#The parser files CLexer.py Clistener.py and Cparser.py
#see /Documents/work/sefcom/gitpatch/antlr.md for more info
def main():
"""
parser,tree = get_tree_from_file('test.c')
print(tree.toStringTree(recog=parser))
printer = KeyPrinter()
walker = ParseTreeWalker()
walker.walk(printer, tree)
"""
if False:
test_functs()
args = get_func_args_from_inp("test_files/test.c", "simple_func",'file')
print(args)
#p,t =get_tree_from_file("test_files/service.i")
p,t =get_tree_from_file("test.service.c.prev")
exit()
#p,t =get_tree_from_file("new_code_expand.c")
print_ctx_bfs(t,"help")
printer=ScopeListener()
walker = ParseTreeWalker()
walker.walk(printer,t)
#for i,k in printer.scopes.items():
# print(f"{type(i)} => {get_string2(i)}")
# print(f"\t {k['func_ctx']}")
# print(f"\t {type(k['parent'])} => {get_string2(k['parent'])}")
x=get_function_info(functions=get_functions(t),fscope=printer.scopes,dont_eval=[])
"""
for key,members in inspect.getmembers(ctx):
print(f"key = {key}\nmember={members}")
"""
def siblings(current):
parent=current.parentCtx
family=list(parent.getChildren())
older=None
younger=None
if len(family)>0:
for i in range(0,len(family)):
if current==family[i]:
break
if i!=0:
younger=family[0:i]
if i!=len(family)-1:
older=family[i+1:]
return younger,older
def get_type_var_info(ctx):
chld=list(ctx.getChildren())
nodes=[]
if len(chld)<=1:
return None,None,None
elif len(chld)==3:
typ=get_string2(chld[0])
node=chld[1]
dec=list(find_multictx(node,[CParser.DeclaratorContext],None,None))
nodes=[(typ,d) for d in dec]
elif len(chld)==2:
checkme=chld[0];
c=list(checkme.getChildren())
typ,node=(None,None)
if len(c)==2:
typ=get_string2(c[0])
node=c[1]
elif len(c)==3:
typ=" ".join([get_string2(x) for x in c[0:2]])
node=c[2]
nodes=[(typ,node)]
else:
return None,None,None
sym_dict=dict()
up_nodes=list()
for t,d in nodes:
if d is None or len(list(d.getChildren()))<1 :
continue
c=list(d.getChild(0).getChildren())
if len(c)>1:
decl_info=""
decl_nodes=list(c[1:])
for i in range(1,len(c)):
decl_info+=" "+get_string2(c[i])
d_=get_string2(c[0])
typ=t+" *"
sym_dict[d_]=typ
up_nodes.extend([(typ,c[0],decl_info)])
up_nodes.extend([(t,d,None)])
return nodes, sym_dict, up_nodes
class ScopeListener(CListener):
cur_scopes=[ [], ]
cur_declarations=[ [], ]
cur_symbol_lut=dict()
cur_assignments=[ [], ]
cur_comparators=[ [], ]
resolved=list()
scopes=dict()
# keys: k, list of nodes that are valid_parent_scopes
# k['ancestors'] : list of parent nodes
# k['ignore_nodes'] : list of nodes that should not be used to evaluate for variables declaration
# k['pscopes'] : list of preceding scope noes
# k['parent'] : immediate parent node
# k['children'] : children nodes
# k['func_ctx'] : function context
valid_parent_scopes=[\
CParser.CompoundStatementContext,\
CParser.IterationStatementContext,\
CParser.SelectionStatementContext,\
CParser.FunctionDefinitionContext\
]
current_fn_ctx=None
current_scope=None
valid_comparators=[\
CParser.RelationalExpressionContext,\
CParser.EqualityExpressionContext\
]
func_names=[]
def set_functions(self,funcs):
if funcs and type(funcs)==list and len(funcs)>0:
self.func_names=copy.copy(funcs)
def get_basic_type_or_expression(self,node):
n_=node
typ=None
expression=None
un_op=None
found=False
i="-"
dprint(f"[get_basic_type_or_expression]")
dprint(f"{type(n_)} : {get_string2(n_)}")
while (type(n_)!=CParser.PrimaryExpressionContext) and not found:
c=list(n_.getChildren())
dprint(f"{i}{type(n_)} {[type(x) for x in c]} {[get_string2(x) for x in c ]}")
i+="-"
if type(n_)==CParser.DigitSequence:
typ="int"
found=True
elif type(n_) in [\
CParser.Identifier,\
CParser.Constant,\
CParser.PrimaryExpressionContext\
]:
expression=get_string2(n_)
found=True
elif type(n_)==CParser.CastExpressionContext:
if len(c)>1 and not typ:
typ=get_string2(c[-3])
expression=get_string2(c[-1])
found=True
n_=c[-1]
elif type(n_)==CParser.PostfixExpressionContext:
if type(c[0])==CParser.PrimaryExpressionContext:
n_=c[0]
else:
if type(c[1])==CParser.TypeNameContext:
n_=c[1]
elif type(c[2])==CParser.TypeNameContext:
n_=c[2]
else:
print("Error: Bad PostFix Expression")
print(f"=>{get_string2(n_)}")
print("Exiting.")
import sys; sys.exit(-1)
elif type(n_)==CParser.UnaryExpressionContext:
if type(c[0])==CParser.UnaryOperatorContext and len(c)==2:
un_op=get_string2(c[0])
if un_op == '!':
typ="bool"
found=True
if type(c[-1]) in [ CParser.PostfixExpressionContext,\
CParser.CastExpressionContext,\
CParser.Identifier ]:
n_=c[-1]
elif type(c[-2])==CParser.TypeNameContext:
n_=c[-2]
else:
print("Error: Bad Unary Expression")
print(f"=>{get_string2(n_)}")
print("Exiting.")
import sys; sys.exit(-1)
elif type(n_) in [CParser.AndExpressionContext,\
CParser.ExclusiveOrExpressionContext,\
CParser.InclusiveOrExpressionContext,\
CParser.ShiftExpressionContext,\
CParser.AdditiveExpressionContext,\
CParser.MultiplicativeExpressionContext\
]:
n_=c[0]
elif type(n_) in [CParser.LogicalAndExpressionContext,\
CParser.RelationalExpressionContext,\
CParser.EqualityExpressionContext,\
CParser.LogicalOrExpressionContext\
]:
if len(c)>1:
typ="bool"
found=True
else:
n_=c[0]
pass
else:
print("Error: Bad Type Expression")
print(f"type {type(n_)} =>{get_string2(n_)}")
print("Exiting.")
import sys; sys.exit(-1)
# end of while ^^
if not found:
expression=get_string2(n_);
return (typ,expression,un_op)
def is_comparator(self,node):
if type(node) not in self.valid_comparators:
return False,None
else:
children=list(node.getChildren())
if len(children)>1:
dprint(f"[is_comparator] {type(node)} => {get_string2(node)}")
vals=list()
for i in range(0,len(children),2):
dprint(f"[{i}] {type(children[i])} => {get_string2(children[i])}")
vals.append(children[i])
return True,vals
else:
return False,None
def find_pruned_nodes(self):
for i in list(self.scopes.keys()):
self.prune(i)
def prune(self,start):
pruned_nodes=[]
for i in self.scopes[start]['ancestors']:
if i:
x=self.right_siblings(i)
if x:
pruned_nodes.extend(x)
self.scopes[start]['ignore_nodes']=pruned_nodes
def siblings(self,current):
return siblings(current)
def left_siblings(self,current):
return self.siblings(current)[0]
def right_siblings(self,current):
return self.siblings(current)[1]
def scopeleft_siblings(self,current):
if type(current)==CParser.FunctionDefinitionContext:
return None
else:
parent=current.parentCtx
family=list(parent.getChildren())
younger=None
if len(family)>0:
for i in range(0,len(family)):
if current==family[i]:
break
younger=family[0:i]
return younger
else:
return self.left_siblings(parent)
def scoperight_siblings(self,current):
if type(current)==CParser.FunctionDefinitionContext:
return None
else:
parent=current.parentCtx
family=list(parent.getChildren())
older=None
if len(family)>0:
for i in range(0,len(family)):
if current==family[i]:
break
older=family[i+1:]
return older
else:
return self.scoperight_siblings(parent)
def get_last_child(self,node):
n=node
if type(n)==tree.Tree.ErrorNodeImpl:
print(f"ERROR: We have a parsetree error with {get_string2(n)} [type={type(n)}]")
print(f"Parent node: {get_string2(n.parentCtx)} [type={type(n.parentCtx)}]")
return n
while type(n) not in [ tree.Tree.TerminalNodeImpl, tree.Tree.ErrorNodeImpl ]:
n=list(n.getChildren())[-1]
if type(n)==tree.Tree.ErrorNodeImpl:
print(f"ERROR: We have a parsetree error with {get_string2(n)} [type={type(n)}]")
print(f"Parent node: {get_string2(n.parentCtx)} [type={type(n.parentCtx)}]")
return n
def get_scope_limits(self,node):
children=list(node.getChildren())
valid_scope=[node]
invalid_scope=[]
corner=False
if type(node)==CParser.FunctionDefinitionContext:
pass
if type(node)==CParser.CompoundStatementContext:
pass
if type(node)==CParser.SelectionStatementContext:
valid_scope=children[:5] # StatementContext
if len(children)>5:
invalid_scope=children[5:]
else:
corner=True
if type(node)==CParser.IterationStatementContext:
valid_scope=children[:5] # StatementContext
if len(children)>5:
invalid_scope=children[5:]
else:
corner=True
return ((valid_scope,invalid_scope),(node,self.get_last_child(valid_scope[-1])),corner)
def is_else(self,node):
return type(node)==tree.Tree.TerminalNodeImpl and node.getText()=="else"
def getParentScopes(self,start):
# add the current node to the previous hierarchy's descendant list
if self.current_scope:
self.cur_symbol_lut[start]=copy.copy(self.cur_symbol_lut[self.current_scope])
else:
self.cur_symbol_lut[start]=dict()
#for i,c in enumerate(list(start.getChildren())):
# print(f" {i} : {type(c)}")
# if i==1:
# print(f" {i}[0] : {get_string2(c.getChild(0).getChild(0))}")
# print(f" {i}[1] : {get_string2(c.getChild(0).getChild(1))}")
# print(f" {i}[2] : {get_string2(c.getChild(0).getChild(2))}")
# print(f" {i}[2] : type : {type(c.getChild(0).getChild(2))}")
self.current_scope=start
self.cur_scopes[-1].append(start)
# create a new list to accumulate descendants
self.cur_scopes.append([])
self.cur_declarations.append([])
self.cur_assignments.append([])
self.cur_comparators.append([])
pscopes=[]
p=[start]
siblings=self.siblings(start)
self.scopes[start]=dict()
self.scopes[start]['children']=list(start.getChildren())
self.scopes[start]['parent']=start.parentCtx
self.scopes[start]['func_ctx']=self.current_fn_ctx
self.scopes[start]['scope_limits']=self.get_scope_limits(start)
self.scopes[start]['siblings']=siblings
done=(type(start)==CParser.FunctionDefinitionContext)
CASE=0
while not done:
dprint(f"{CASE} : {type(p[-1])} [start? {p[-1]==start}]")
CASE+=1
if p[-1] == start:
p.append(p[-1].parentCtx)
continue
if type(p[-1]) in self.valid_parent_scopes:
capture=True
x=min(5,len(p))
dprint(f"Valid scope parent: {type(p[-1])}")
dprint(f" ===> Last {x} parents! ")
for i in range(0,x):
dprint(f" [{i}] : {type(p[i-x])} ")
# [ {get_string2(p[x-i-1])} ]")
if type(p[-1])==CParser.SelectionStatementContext:
lsiblings=self.left_siblings(p[-2])
for i in range(0,len(lsiblings)):
dprint(f" sibling [{i}] : {type(lsiblings[i])} [ {get_string2(lsiblings[i])} ]")
pass
if self.is_else(lsiblings[-1]):
dprint(f"In an else condition, don't capture {type(p[-1])}")
capture=False
if capture:
pscopes.append(p[-1])
if p[-1] in self.resolved:
dprint(f"RESOLVED : {type(start)} => {type(p[-1])} ")
last=p.pop()
if type(last) == CParser.FunctionDefinitionContext:
done=True
break
else:
x=self.scopes.get(last,None)
if x:
dprint(f" converged parent => {type(last)}")
pscopes.extend(x['pscopes'])
p.extend(x['ancestors'])
done=True
break
p.append(p[-1].parentCtx)
self.scopes[start]['pscopes']=pscopes
self.scopes[start]['ancestors']=p
self.resolved.append(start)
def exitExternalDeclaration(self,ctx:CParser.ExternalDeclarationContext):
pass
def enterExternalDeclaration(self,ctx:CParser.ExternalDeclarationContext):
pass
def exitCompoundStatement(self,ctx:CParser.CompoundStatementContext):
x=self.cur_scopes.pop()
self.current_scope=self.cur_scopes[-1][-1]
dprint(f"Descendants of {type(ctx)} : {get_string2(ctx)}")
for i in range(0,len(x)):
dprint(f" {i} : {type(x[i])} [ {get_string2(x[i])} ]")
self.scopes[ctx]['descendants']=copy.copy(x)
x=self.cur_symbol_lut[ctx]
self.scopes[ctx]['sym_lut']=copy.copy(x)
x=self.cur_declarations.pop()
self.scopes[ctx]['decls']=copy.copy(x)
x=self.cur_assignments.pop()
self.scopes[ctx]['assigns']=copy.copy(x)
s=[(n[0],n[1],n[2],get_string2(n[3])) for n in x]
dprint(f"Assigns = {s}")
x=self.cur_comparators.pop()
self.scopes[ctx]['compares']=copy.copy(x)
s=[(n[0],n[1],n[2],type(n[3]),get_string2(n[3])) for n in x]
dprint(f"Compares = {s}")
pass
def enterCompoundStatement(self,ctx:CParser.CompoundStatementContext):
x=self.scopes.get(ctx,None)
if x:
print("[DuplicateNodeError] {get_string2(ctx)}")
else:
self.getParentScopes(ctx)
pass
def exitSelectionStatement(self, ctx:CParser.SelectionStatementContext):
x=self.cur_scopes.pop()
self.current_scope=self.cur_scopes[-1][-1]
dprint(f"Descendants of {type(ctx)} : {get_string2(ctx)}")
for i in range(0,len(x)):
dprint(f" {i} : {type(x[i])} [ {get_string2(x[i])} ]")
self.scopes[ctx]['descendants']=copy.copy(x)
x=self.cur_symbol_lut[ctx]
self.scopes[ctx]['sym_lut']=copy.copy(x)
x=self.cur_declarations.pop()
self.scopes[ctx]['decls']=copy.copy(x)
x=self.cur_assignments.pop()
self.scopes[ctx]['assigns']=copy.copy(x)
x=self.cur_comparators.pop()
self.scopes[ctx]['compares']=copy.copy(x)
pass
def enterSelectionStatement(self, ctx:CParser.SelectionStatementContext):
x=self.scopes.get(ctx,None)
if x:
print("[DuplicateNodeError] {get_string2(ctx)}")
else:
self.getParentScopes(ctx)
pass
def exitIterationStatement(self, ctx:CParser.IterationStatementContext):
x=self.cur_scopes.pop()
self.current_scope=self.cur_scopes[-1][-1]
dprint(f"Descendants of {type(ctx)} : {get_string2(ctx)}")
for i in range(0,len(x)):
dprint(f" {i} : {type(x[i])} [ {get_string2(x[i])} ]")
self.scopes[ctx]['descendants']=copy.copy(x)
x=self.cur_symbol_lut[ctx]
self.scopes[ctx]['sym_lut']=copy.copy(x)
x=self.cur_declarations.pop()
self.scopes[ctx]['decls']=copy.copy(x)
x=self.cur_assignments.pop()
self.scopes[ctx]['assigns']=copy.copy(x)
x=self.cur_comparators.pop()
self.scopes[ctx]['compares']=copy.copy(x)
pass
def enterIterationStatement(self, ctx:CParser.IterationStatementContext):
x=self.scopes.get(ctx,None)
if x:
print("[DuplicateNodeError] {get_string2(ctx)}")
else:
self.getParentScopes(ctx)
pass
def enterFunctionDefinition(self,ctx:CParser.FunctionDefinitionContext):
self.current_fn_ctx=ctx
x=self.scopes.get(ctx,None)
c=list(ctx.getChildren())
dprint(f"[enterFunctionDefinition]")
dprint(f"{[(type(c[x]),get_string2(c[x])) for x in range(0,len(c)-1)]}")
if x:
print("[DuplicateNodeError] {get_string2(ctx)}")
else:
self.getParentScopes(ctx)
pass
def exitFunctionDefinition(self,ctx:CParser.FunctionDefinitionContext):
self.find_pruned_nodes()
self.current_fn_ctx=None
x=self.cur_scopes.pop()
self.current_scope=None
dprint(f"Descendants of {type(ctx)} : {get_string2(ctx)}")
for i in range(0,len(x)):
dprint(f" {i} : {type(x[i])} [ {get_string2(x[i])} ]")
self.scopes[ctx]['descendants']=copy.copy(x)
x=self.cur_symbol_lut[ctx]
self.scopes[ctx]['sym_lut']=copy.copy(x)
x=self.cur_declarations.pop()
self.scopes[ctx]['decls']=copy.copy(x)
x=self.cur_assignments.pop()
self.scopes[ctx]['assigns']=copy.copy(x)
x=self.cur_comparators.pop()
self.scopes[ctx]['compares']=copy.copy(x)
pass
def exitRelationalExpression(self, ctx:CParser.RelationalExpressionContext):
pass
def enterRelationalExpression(self, ctx:CParser.RelationalExpressionContext):
comp,values=self.is_comparator(ctx)
if comp:
typ=None
expr=None
un_op=None
dprint(f"[enterRelationalExpression] : {type(ctx)} => {get_string2(ctx)}")
dprint(f"=> {[get_string2(x) for x in values]}")
for x in values:
#str_x=get_string2(x)
typ,expr,un_op=self.get_basic_type_or_expression(x)
if typ != None:
dprint(f"FOUND IT! [1.1] {typ} : {expr}")
break
typ=self.cur_symbol_lut[self.current_scope].get(expr,None)
if typ != None:
dprint(f"FOUND IT! [1.2] {typ} : {expr}")
break
# note from pdr: i don't think this is particularly robust, but oh well. good luck to me
if not typ:
typ="UNDEF"
if un_op:
if un_op in ['+','-','~']:
typ='int'
elif un_op in ['!']:
typ='bool'
if un_op=="*" and "*" in typ:
typ=typ.replace(" *","",1)
elif un_op=="&":
typ=typ+" *"
dprint(f"Resolved type: [1.3] {typ} : {expr}")
for x in values:
# the point here is to somewhat take advantage of existing tuple structure for reuse
self.cur_comparators[-1].extend([(typ,"","",x)])
pass
def exitEqualityExpression(self, ctx:CParser.EqualityExpressionContext):
pass
def enterEqualityExpression(self, ctx:CParser.EqualityExpressionContext):
comp,values=self.is_comparator(ctx)
if comp:
typ=None
expr=None
un_op=None
dprint(f"[enterEqualityExpression] : {type(ctx)} => {get_string2(ctx)}")
dprint(f"=> {[get_string2(x) for x in values]}")
for x in values:
#str_x=get_string2(x)
typ,expr,un_op=self.get_basic_type_or_expression(x)
if typ != None:
dprint(f"FOUND IT! [2.1] {typ} : {expr}")
break
typ=self.cur_symbol_lut[self.current_scope].get(expr,None)
if typ != None:
dprint(f"FOUND IT! [2.2] {typ} : {expr}")
break
if not typ:
typ="UNDEF"
if un_op:
if un_op in ['+','-','~']:
typ='int'
elif un_op in ['!']:
typ='bool'
if un_op=="*" and "*" in typ:
typ=typ.replace(" *","",1)
elif un_op=="&":
typ=typ+" *"
dprint(f"Resolved type: [2.3] {typ} : {expr}")
for x in values:
self.cur_comparators[-1].extend([(typ,"","",x)])
pass
def exitAssignmentExpression(self, ctx:CParser.AssignmentExpressionContext):
pass
def enterAssignmentExpression(self, ctx:CParser.AssignmentExpressionContext):
if self.current_scope is None or self.cur_symbol_lut[self.current_scope] is None:
dprint(f"[WARNING] : self.current_scope = '{self.current_scope}'")
dprint(f"[WARNING] : self.cur_symbol_lut[self.current_scope] = '{self.cur_symbol_lut.get(self.current_scope,None)}'")
dprint(f"[WARNING] ctx : {get_string2(ctx)}")
pass
chld=list(ctx.getChildren())
if len(chld)==3 and "=" in get_string2(chld[1]):
#nodes=get_string2(ctx)
ovar=get_string2(chld[0])
var_ext=ovar.split('[',1) if '[' in ovar else [ovar,""]
var=var_ext[0]
ext=var_ext[1]
if ext!="":
ext="["+ext
nodes=chld[2]
dprint(f"var: {var} ({ovar}) = {get_string2(nodes)}")
typ=self.cur_symbol_lut[self.current_scope].get(var,"UNDEF")
dprint(f"var: {typ} {var} ({ovar}) = {get_string2(nodes)}")
if ovar!=var:
typ=typ.rsplit(' *',1)[0]
self.cur_assignments[-1].extend([(typ,var,ext,nodes)])
else:
pass
pass
#def exitInitializer(self, ctx:CParser.InitializerContext):
# pass
#def enterInitializer(self, ctx:CParser.InitializerContext):
# if type(ctx.getChild(0))==CParser.AssignmentExpressionContext:
# nodes=get_string2(ctx)
# print(f"Initializer: {nodes}")
# self.cur_assignments[-1].extend([nodes])
# pass
#rules_with_declarations=[CParser.ForDeclarationContext,CParser.DeclarationContext]
def exitDeclaration(self, ctx:CParser.DeclarationContext):
pass
def enterDeclaration(self, ctx:CParser.DeclarationContext):
if self.current_scope==None:
pass
else:
chld=list(ctx.getChildren())
nodes=[]
dprint(f"[enterDeclaration] {[(type(c),get_string2(c)) for c in chld]}")
if len(chld)<=1:
return
elif len(chld)==3:
typ=get_string2(chld[0])
node=chld[1]
dec=list(find_multictx(node,[CParser.DeclaratorContext],None,None))
nodes=[(typ,d) for d in dec]
elif len(chld)==2:
checkme=chld[0];
c=list(checkme.getChildren())
typ,node=(None,None)
if len(c)==2:
typ=get_string2(c[0])
node=c[1]
elif len(c)==3:
typ=" ".join([get_string2(x) for x in c[0:2]])
node=c[2]
nodes=[(typ,node)]
else:
return
sym_dict=dict()
up_nodes=list()
i=-1
for t,d in nodes:
i+=1
if d is None or len(list(d.getChildren()))<1 :
continue
if t in self.func_names:
continue
c=list(d.getChild(0).getChildren())
if len(c)>1:
decl_info=""
decl_nodes=list(c[1:])
for i in range(1,len(c)):
decl_info+=" "+get_string2(c[i])
d_=get_string2(c[0])
typ=t+" *"
sym_dict[d_]=typ
dprint(f"[A-t-{i}] sym_dict [{get_string2(d_)}] = {typ} ")
up_nodes.extend([(typ,c[0],decl_info)])
if type(c[0])!=tree.Tree.TerminalNodeImpl:
c0=list(c[0].getChildren())
if len(c0)>1:
dl_info=""
dl_nodes=list(c0[1:])
for i in range(1,len(c)):
dl_info+=" "+get_string2(c[i])
dl_info+=decl_info
typ+="*"
d_=get_string2(c0[0])
sym_dict[d_]=typ
dprint(f"[B-t-{i}] sym_dict [{get_string2(d_)}] = {typ} ")
up_nodes.extend([(typ,c0[0],dl_info)])
up_nodes.extend([(t,d,None)])
dprint(f"[C-t-{i}] sym_dict [{get_string2(d)}] = {t} ")
sym_dict[get_string2(d)]=t
self.cur_declarations[-1].extend(up_nodes)
try:
self.cur_symbol_lut[self.current_scope].update(sym_dict)
except Exception as e:
print(e)
print(f"=> {type(self.current_scope)}")
print(f"ctx => {get_string2(ctx)}")
raise(e)
pass
def exitForDeclaration(self, ctx:CParser.ForDeclarationContext):
pass
def enterForDeclaration(self, ctx:CParser.ForDeclarationContext):
chld=list(ctx.getChildren())
if len(chld)>=2:
typ=get_string2(chld[0])
try:
node=chld[1]
except:
print(f"[enterForDeclaration] len(chld)={len(chld)}")
raise
dec=list(find_multictx(node,[CParser.DeclaratorContext],None,None))
dprint(f"[enterForDeclaration]")
nodes=[(typ,d) for d in dec]
up_nodes=list()
sym_dict=dict()
if len(nodes)==0:
return
i=-1
for t,d in nodes:
i+=1
if d is None or len(list(d.getChildren()))<1 :
continue
if t in self.func_names:
continue
c=list(d.getChild(0).getChildren())
if len(c)>1:
decl_info=""
decl_nodes=list(c[1:])
for i in range(1,len(c)):
decl_info+=" "+get_string2(c[i])
d_=get_string2(c[0])
typ=t+" *"
sym_dict[d_]=typ
dprint(f"[A-t-{i}] sym_dict [{get_string2(d_)}] = {typ} [# children={len(c)}]")
up_nodes.extend([(typ,c[0],decl_info)])
if type(c[0])!=tree.Tree.TerminalNodeImpl:
c0=list(c[0].getChildren())
if len(c0)>1:
dl_info=""
dl_nodes=list(c0[1:])
for i in range(1,len(c)):
dl_info+=" "+get_string2(c[i])
dl_info+=decl_info
typ+="*"
d_=get_string2(c0[0])
sym_dict[d_]=typ
dprint(f"[B-t-{i}] sym_dict [{get_string2(d_)}] = {typ} ")
up_nodes.extend([(typ,c0[0],dl_info)])
up_nodes.extend([(t,d,None)])
dprint(f"[C-t-{i}] sym_dict [{get_string2(d)}] = {t} ")
sym_dict[get_string2(d)]=t
self.cur_declarations[-1].extend(up_nodes)
self.cur_symbol_lut[self.current_scope].update(sym_dict)
pass
def exitParameterDeclaration(self, ctx:CParser.ParameterDeclarationContext):
pass
def enterParameterDeclaration(self, ctx:CParser.ParameterDeclarationContext):
if not self.current_scope:
dprint("[CORNER CASE] Parameter Declaration, current_scope is None?")
dprint(f"current: {get_string2(ctx)}")
else:
chld=list(ctx.getChildren())
typ=get_string2(chld[0])
if len(chld)>1 and typ!=CParser.DeclarationSpecifiers2Context:
node=chld[1]
dprint(f"ParameterDeclaration : type = {typ}, var = {get_string2(node)} [type={type(node)}]")
dec=[node]
if type(node)!=CParser.DeclaratorContext:
dec=list(find_multictx(node,[CParser.DeclaratorContext],None,None))
dprint(f" dec = {[get_string2(d) for d in dec]}")
nodes=[(typ,d) for d in dec]
up_nodes=list()
sym_dict=dict()
for t,d in nodes:
if d is None or len(list(d.getChildren()))<1 :
continue
if t in self.func_names:
continue
dprint(f"[enterParameterDeclaration] {t} : {get_string2(d)}")
c=list(d.getChild(0).getChildren())
if len(c)>1:
decl_info=""
decl_nodes=list(c[1:])
for i in range(1,len(c)):
decl_info+=" "+get_string2(c[i])
d_=get_string2(c[0])
typ=t+" *"
sym_dict[d_]=typ
dprint(f"sym_dict [{get_string2(d_)}] = {typ} ")
up_nodes.extend([(typ,c[0],decl_info)])
up_nodes.extend([(t,d,None)])
self.cur_declarations[-1].extend(up_nodes)
for a,b in nodes:
if b is None or len(list(b.getChildren()))<1 :
continue
if a in self.func_names:
continue
dprint(f"sym_dict [{get_string2(b)}] = {a} ")
sym_dict[get_string2(b)]=a
self.cur_symbol_lut[self.current_scope].update(sym_dict)
else:
dprint(f"[CORNER CASE] ParameterDeclaration : children = {[(type(v),get_string2(v)) for v in chld]} => setting default type to 'int'")
sym_dict=dict()
sym_dict[get_string2(chld[0])]="int";
self.cur_symbol_lut[self.current_scope].update(sym_dict)
pass
pass
class KeyPrinter(CListener):
def enterSelectionStatement(self, ctx):
print(f"Enter Selection Statement\n{ctx.getText()}")
pass
def enterFunctionDefinition(self,ctx):
print("Found function: '"+str(ctx.declarator().directDeclarator().directDeclarator().Identifier())+"'")
print(f"Function content {self.function_content}")
print ("Looking for '"+self.function+"'")
if str(ctx.declarator().directDeclarator().directDeclarator().Identifier())==self.function:
print("Found it! "+self.function)
self.enable_dumping=True
def dprint(instr,flush=False):
if debug[0]:
print(instr,flush=flush)
else:
global gbl_debug_msg
if gbl_debug_msg[3]:
if gbl_debug_msg[1]%50 == 0:
flush=True
gbl_debug_msg[0]+=instr+"\n"
gbl_debug_msg[1]+=1
if flush:
write_log()
gbl_debug_msg[0]=""
def write_log():
if gbl_debug_msg[3]:
gbl_debug_msg[2].write(gbl_debug_msg[0])
def get_tree(inp):
lexer = CLexer(inp)
stream = CommonTokenStream(lexer)
stream.fill()
parser = CParser(stream)
#compilationUnit is the "base case" for the grammer described
#in C.g4
tree = parser.compilationUnit()
return parser,tree
def get_tree_from_file(file_name):
inp = FileStream(file_name)
return get_tree(inp)
def get_tree_from_string(inp):
inp = InputStream(inp)
return get_tree(inp)
def print_ctx_bfs(tree,outf):
q = linked_list.ll()
#get first set of children
q.push_list(list(tree.getChildren()))
#go through all children breadth first
txt = ""
while q.length > 0 :
e = q.dequeue()
txt += f"Text={e.getText()}\nType={type(e)}\n"
txt += f"Child Count = {e.getChildCount()}\n"
if e.getChildCount()>0:
for i,c in enumerate(list(e.getChildren())):
txt+=f"{i} : {type(c)} [{c.getText()}]\n"
txt += "-------\n"
if e.getChildCount() != 0:
q.push_list(list(e.getChildren()))
with open(outf, 'w') as outfile:
outfile.write(txt)
"""
outfile = open(outf, 'w')
outfile.write(txt)
"""
#get all types of ctx
#use to find functions or conditional statements
def find_ctx(tree,ctx,screen=None):
q = []
#get first set of children
pushq(q, list(tree.getChildren()))
#go through all children breadth first
r = []
while q != []:
e = popq(q)
if screen and type(e) in screen:
continue
t = type(e)
if str(t) == ctx:
r.append(e)
if e.getChildCount() != 0:
pushq(q,list(e.getChildren()))
return r
#get all types of ctx
#use to find functions or conditional statements
def find_ctx_list(tree,ctx,screen=None):
q = []
#get first set of children
pushq(q, list(tree.getChildren()))
#go through all children breadth first
r = []
while q != []:
e = popq(q)
if screen and type(e) in screen:
continue
t = type(e)
if str(t) in ctx:
r.append(e)
if e.getChildCount() != 0:
pushq(q,list(e.getChildren()))
return r
#Input: a functionDefinitionContext
#Output: the argument names
def get_func_name(fctx):
gtx = fctx.getText()
node=None
if type(fctx)==CParser.FunctionDefinitionContext:
node=fctx.declarator()
else:
node=fctx.funcDeclarator()
if node.getChild(0).getChild(0).getText().strip() == '(':
ret = fctx.getChild(0).getText()
else:
ret = node.getChild(0).getChild(0).getText()
if ret == '*':
ret = node.getChild(1).getChild(0).getText()
return ret
def find_multictx_with_scope(tree,multctx,screen=None,ignore_nodes=None,okay_subscope=None):
if not tree:
return None
q = []
#get first set of children
pushq(q, list(tree.getChildren()))
#go through all children breadth first
txt = ""
r = []
start_scope=type(tree)
check_scope=any([((screen!=None) and (start_scope in screen)), (okay_subscope!=None)])
screen_me=screen
if check_scope:
if not screen_me:
screen_me=[]
screen_me+=okay_subscope
dprint(f"scope info: start = {start_scope}, check_scope = {check_scope}")
while q != []:
e = popq(q)
if (check_scope and okay_subscope and type(e) in okay_subscope):
check_scope=False
screen_me+=okay_subscope
if (screen_me and type(e) in screen_me) or (ignore_nodes and e in ignore_nodes):
continue
txt += f"Text={e.getText()}\nType={type(e)}\n"
txt += "-------\n"
t = type(e)
if t in multctx: