-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_script.py
More file actions
1651 lines (1429 loc) · 68.7 KB
/
test_script.py
File metadata and controls
1651 lines (1429 loc) · 68.7 KB
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
import tkinter as tk
from tkinter import ttk, font, filedialog
import sys
import io
from lexer import lexer, tokenize, format_token_output
from myparser import parser
from interpreter import Interpreter
import re
from ast_nodes import * # Import all AST node classes at the top of script.py
# ---------- Functions ----------
def go_to_learning():
"""Show the learning screen."""
hide_all()
learn_screen.pack(fill=tk.BOTH, expand=True)
def go_to_testing():
"""Show the testing screen."""
hide_all()
testing_screen.pack(fill=tk.BOTH, expand=True)
def go_to_optimizer():
"""Show the optimizer screen."""
hide_all()
optimizer_screen.pack(fill=tk.BOTH, expand=True)
def go_to_compiler_phases():
"""Show the compiler phases screen."""
hide_all()
compiler_phases_screen.pack(fill=tk.BOTH, expand=True)
def back_to_welcome():
"""Return to the welcome screen."""
hide_all()
welcome_screen.pack(fill=tk.BOTH, expand=True)
def hide_all():
"""Hide all main screens."""
welcome_screen.pack_forget()
testing_screen.pack_forget()
compiler_phases_screen.pack_forget()
optimizer_screen.pack_forget()
learn_screen.pack_forget()
def execute_code():
"""Execute code from the testing screen."""
code = input_text.get("1.0", tk.END)
output_box.config(state=tk.NORMAL)
output_box.delete("1.0", tk.END)
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
try:
exec(code, globals())
output = redirected_output.getvalue()
output_box.insert(tk.END, output)
except Exception as e:
output_box.insert(tk.END, f"Error: {e}")
finally:
sys.stdout = old_stdout
output_box.config(state=tk.DISABLED)
def optimize_ast(node):
# Recursively optimize AST nodes (constant folding, etc.)
if isinstance(node, BinaryOp):
left = optimize_ast(node.left)
right = optimize_ast(node.right)
if isinstance(left, Number) and isinstance(right, Number):
if node.op == '+': return Number(left.value + right.value)
if node.op == '-': return Number(left.value - right.value)
if node.op == '*': return Number(left.value * right.value)
if node.op == '/': return Number(left.value / right.value)
return BinaryOp(left, node.op, right)
elif isinstance(node, UnaryOp):
expr = optimize_ast(node.expr)
if isinstance(expr, Number):
if node.op == '-': return Number(-expr.value)
return UnaryOp(node.op, expr)
elif isinstance(node, Assign):
return Assign(node.name, optimize_ast(node.expr))
elif isinstance(node, Print):
return Print(optimize_ast(node.expr))
elif isinstance(node, IfElse):
cond = optimize_ast(node.condition)
if isinstance(cond, Boolean):
if cond.value:
return [optimize_ast(stmt) for stmt in node.if_body]
elif node.else_body:
return [optimize_ast(stmt) for stmt in node.else_body]
else:
return []
return IfElse(cond, [optimize_ast(stmt) for stmt in node.if_body], [optimize_ast(stmt) for stmt in node.else_body] if node.else_body else None)
elif isinstance(node, WhileLoop):
return WhileLoop(optimize_ast(node.condition), [optimize_ast(stmt) for stmt in node.body])
elif isinstance(node, ForLoop):
return ForLoop(node.var, optimize_ast(node.iterable), [optimize_ast(stmt) for stmt in node.body])
elif isinstance(node, FunctionDef):
return FunctionDef(node.name, node.params, [optimize_ast(stmt) for stmt in node.body])
elif isinstance(node, FunctionCall):
return FunctionCall(node.name, [optimize_ast(arg) for arg in node.args])
elif isinstance(node, ListNode):
return ListNode([optimize_ast(elem) for elem in node.elements])
elif isinstance(node, IndexNode):
return IndexNode(optimize_ast(node.expr), optimize_ast(node.index))
elif isinstance(node, StringMethod):
return StringMethod(optimize_ast(node.expr), node.method, [optimize_ast(arg) for arg in node.args])
elif isinstance(node, LenFunction):
return LenFunction(optimize_ast(node.expr))
elif isinstance(node, RangeCall):
return RangeCall(optimize_ast(node.start) if node.start else None, optimize_ast(node.stop) if node.stop else None, optimize_ast(node.step) if node.step else None)
else:
return node
def ast_to_code(node):
# Recursively convert AST back to code
if isinstance(node, Assign):
return f"{ast_to_code(node.name)} = {ast_to_code(node.expr)}"
elif isinstance(node, BinaryOp):
return f"({ast_to_code(node.left)} {node.op} {ast_to_code(node.right)})"
elif isinstance(node, UnaryOp):
return f"{node.op}{ast_to_code(node.expr)}"
elif isinstance(node, Number):
return str(node.value)
elif isinstance(node, String):
return repr(node.value)
elif isinstance(node, Boolean):
return str(node.value)
elif isinstance(node, Identifier):
return node.name
elif isinstance(node, Print):
return f"print({ast_to_code(node.expr)})"
elif isinstance(node, IfElse):
code = f"if {ast_to_code(node.condition)}:\n"
for stmt in node.if_body:
code += f" {ast_to_code(stmt)}\n"
if node.else_body:
code += f"else:\n"
for stmt in node.else_body:
code += f" {ast_to_code(stmt)}\n"
return code.rstrip()
elif isinstance(node, WhileLoop):
code = f"while {ast_to_code(node.condition)}:\n"
for stmt in node.body:
code += f" {ast_to_code(stmt)}\n"
return code.rstrip()
elif isinstance(node, ForLoop):
code = f"for {ast_to_code(node.var)} in {ast_to_code(node.iterable)}:\n"
for stmt in node.body:
code += f" {ast_to_code(stmt)}\n"
return code.rstrip()
elif isinstance(node, FunctionDef):
code = f"def {node.name}({', '.join(ast_to_code(param) for param in node.params)}):\n"
for stmt in node.body:
code += f" {ast_to_code(stmt)}\n"
return code.rstrip()
elif isinstance(node, FunctionCall):
return f"{ast_to_code(node.name)}({', '.join(ast_to_code(arg) for arg in node.args)})"
elif isinstance(node, ListNode):
return f"[{', '.join(ast_to_code(elem) for elem in node.elements)}]"
elif isinstance(node, IndexNode):
return f"{ast_to_code(node.expr)}[{ast_to_code(node.index)}]"
elif isinstance(node, StringMethod):
return f"{ast_to_code(node.expr)}.{node.method}({', '.join(ast_to_code(arg) for arg in node.args)})"
elif isinstance(node, LenFunction):
return f"len({ast_to_code(node.expr)})"
elif isinstance(node, RangeCall):
args = [ast_to_code(arg) for arg in [node.start, node.stop, node.step] if arg is not None]
return f"range({', '.join(args)})"
elif isinstance(node, Return):
return f"return {ast_to_code(node.expr)}"
elif isinstance(node, Break):
return "break"
elif isinstance(node, Continue):
return "continue"
elif isinstance(node, TryExcept):
code = f"try:\n"
for stmt in node.try_body:
code += f" {ast_to_code(stmt)}\n"
code += f"except:\n"
for stmt in node.except_body:
code += f" {ast_to_code(stmt)}\n"
return code.rstrip()
else:
return ""
def optimize_code():
raw_code = optimizer_input.get("1.0", tk.END).strip()
optimizer_output.config(state=tk.NORMAL)
optimizer_output.delete("1.0", tk.END)
if not raw_code:
optimizer_output.insert(tk.END, "⚠️ Please enter some Python code to optimize.")
optimizer_output.config(state=tk.DISABLED)
return
try:
ast = parser.parse(raw_code)
if ast is None:
raise Exception("Failed to parse code")
# Optimize each statement in the AST
optimized_ast = []
for node in ast:
opt = optimize_ast(node)
if isinstance(opt, list):
optimized_ast.extend(opt)
else:
optimized_ast.append(opt)
# Convert optimized AST back to code
optimized_code = "\n".join(ast_to_code(node) for node in optimized_ast if node)
optimizer_output.insert(tk.END, optimized_code)
except Exception as e:
optimizer_output.insert(tk.END, f"❌ Error during optimization:\n{str(e)}")
optimizer_output.config(state=tk.DISABLED)
def copy_to_clipboard():
optimized_code = optimizer_output.get("1.0", tk.END)
root.clipboard_clear()
root.clipboard_append(optimized_code)
root.update()
def download_optimized_code():
optimized_code = optimizer_output.get("1.0", tk.END)
if not optimized_code.strip():
return
file_path = filedialog.asksaveasfilename(
defaultextension=".py",
filetypes=[("Python Files", "*.py"), ("All Files", "*.*")],
title="Save Optimized Code"
)
if file_path:
with open(file_path, "w", encoding="utf-8") as f:
f.write(optimized_code)
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def toggle_section(frame):
if frame.winfo_viewable():
frame.pack_forget()
else:
frame.pack(fill="x", padx=20, pady=(0, 10))
# --- Helper to ensure all phase functions handle both lists and single nodes ---
def ensure_list(ast):
if isinstance(ast, list):
return ast
elif ast is None:
return []
else:
return [ast]
# Define the original pretty_print_ast function first
def pretty_print_ast(node, indent="", is_last=True):
# Define prefix based on whether it's the last child
prefix = "└── " if is_last else "├── "
if isinstance(node, list):
result = []
for i, n in enumerate(node):
result.append(pretty_print_ast(n, indent, i == len(node) - 1))
return "\n".join(result)
elif hasattr(node, "__class__"):
cname = node.__class__.__name__
if cname == "Assign":
return f"{indent}{prefix}Assignment\n{indent} ├── Variable: {node.name}\n{indent} └── Value: {pretty_print_ast(node.expr, indent + ' ', True)}"
elif cname == "BinaryOp":
return f"{indent}{prefix}Binary Operation: {node.op}\n{indent} ├── Left: {pretty_print_ast(node.left, indent + ' ', False)}\n{indent} └── Right: {pretty_print_ast(node.right, indent + ' ', True)}"
elif cname == "UnaryOp":
return f"{indent}{prefix}Unary Operation: {node.op}\n{indent} └── Expression: {pretty_print_ast(node.expr, indent + ' ', True)}"
elif cname == "Number":
return f"{indent}{prefix}Number: {node.value}"
elif cname == "String":
return f"{indent}{prefix}String: '{node.value}'"
elif cname == "Boolean":
return f"{indent}{prefix}Boolean: {node.value}"
elif cname == "Identifier":
return f"{indent}{prefix}Identifier: {node.name}"
elif cname == "Print":
return f"{indent}{prefix}Print Statement\n{indent} └── Expression: {pretty_print_ast(node.expr, indent + ' ', True)}"
elif cname == "IfElse":
result = [f"{indent}{prefix}If-Else Statement"]
result.append(f"{indent} ├── Condition: {pretty_print_ast(node.condition, indent + ' ', False)}")
result.append(f"{indent} ├── If Body:")
for i, stmt in enumerate(node.if_body):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.if_body) - 1 and not node.else_body))
if node.else_body:
result.append(f"{indent} └── Else Body:")
for i, stmt in enumerate(node.else_body):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.else_body) - 1))
return "\n".join(result)
elif cname == "WhileLoop":
result = [f"{indent}{prefix}While Loop"]
result.append(f"{indent} ├── Condition: {pretty_print_ast(node.condition, indent + ' ', False)}")
result.append(f"{indent} └── Body:")
for i, stmt in enumerate(node.body):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.body) - 1))
return "\n".join(result)
elif cname == "ForLoop":
result = [f"{indent}{prefix}For Loop"]
result.append(f"{indent} ├── Variable: {node.var}")
result.append(f"{indent} ├── Iterable: {pretty_print_ast(node.iterable, indent + ' ', False)}")
result.append(f"{indent} └── Body:")
for i, stmt in enumerate(node.body):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.body) - 1))
return "\n".join(result)
elif cname == "FunctionDef":
result = [f"{indent}{prefix}Function Definition: {node.name}"]
result.append(f"{indent} ├── Parameters: {', '.join(str(p) for p in node.params)}")
result.append(f"{indent} └── Body:")
for i, stmt in enumerate(node.body):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.body) - 1))
return "\n".join(result)
elif cname == "FunctionCall":
result = [f"{indent}{prefix}Function Call: {node.name}"]
result.append(f"{indent} └── Arguments:")
for i, arg in enumerate(node.args):
result.append(pretty_print_ast(arg, indent + ' ', i == len(node.args) - 1))
return "\n".join(result)
elif cname == "ListNode":
result = [f"{indent}{prefix}List"]
for i, elem in enumerate(node.elements):
result.append(pretty_print_ast(elem, indent + ' ', i == len(node.elements) - 1))
return "\n".join(result)
elif cname == "IndexNode":
return f"{indent}{prefix}List Index\n{indent} ├── List: {pretty_print_ast(node.list_expr, indent + ' ', False)}\n{indent} └── Index: {pretty_print_ast(node.index_expr, indent + ' ', True)}"
elif cname == "ListAssign":
return f"{indent}{prefix}List Assignment\n{indent} ├── List: {pretty_print_ast(node.list_expr, indent + ' ', False)}\n{indent} ├── Index: {pretty_print_ast(node.index_expr, indent + ' ', False)}\n{indent} └── Value: {pretty_print_ast(node.value, indent + ' ', True)}"
elif cname == "Return":
return f"{indent}{prefix}Return Statement\n{indent} └── Value: {pretty_print_ast(node.expr, indent + ' ', True)}"
elif cname == "Break":
return f"{indent}{prefix}Break Statement"
elif cname == "Continue":
return f"{indent}{prefix}Continue Statement"
elif cname == "TryExcept":
result = [f"{indent}{prefix}Try-Except Block"]
result.append(f"{indent} ├── Try Block:")
for i, stmt in enumerate(node.try_block):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.try_block) - 1))
result.append(f"{indent} └── Except Block:")
for i, stmt in enumerate(node.except_block):
result.append(pretty_print_ast(stmt, indent + ' ', i == len(node.except_block) - 1))
return "\n".join(result)
elif cname == "StringMethod":
result = [f"{indent}{prefix}String Method: {node.method}"]
result.append(f"{indent} ├── String: {pretty_print_ast(node.string_obj, indent + ' ', False)}")
if hasattr(node, 'args') and node.args:
result.append(f"{indent} └── Arguments:")
for i, arg in enumerate(node.args):
result.append(pretty_print_ast(arg, indent + ' ', i == len(node.args) - 1))
return "\n".join(result)
elif cname == "LenFunction":
return f"{indent}{prefix}Length Function\n{indent} └── Expression: {pretty_print_ast(node.expr, indent + ' ', True)}"
elif cname == "RangeCall":
result = [f"{indent}{prefix}Range Function"]
if node.start:
result.append(f"{indent} ├── Start: {pretty_print_ast(node.start, indent + ' ', False)}")
if node.stop:
result.append(f"{indent} ├── Stop: {pretty_print_ast(node.stop, indent + ' ', False)}")
if node.step:
result.append(f"{indent} └── Step: {pretty_print_ast(node.step, indent + ' ', True)}")
return "\n".join(result)
else:
return f"{indent}{prefix}Unknown Node: {cname}"
else:
return f"{indent}{prefix}Unknown: {str(node)}"
# Now patch the functions after they're defined
old_pretty_print_ast = pretty_print_ast
def pretty_print_ast(node, indent="", is_last=True):
node = ensure_list(node)
if isinstance(node, list) and len(node) == 1:
return old_pretty_print_ast(node[0], indent, is_last)
elif isinstance(node, list):
result = []
for i, n in enumerate(node):
result.append(old_pretty_print_ast(n, indent, i == len(node) - 1))
return "\n".join(result)
else:
return old_pretty_print_ast(node, indent, is_last)
# Define the original semantic_analysis function
def semantic_analysis(ast):
symbol_table = {}
errors = []
type_info = {}
def get_type(value):
if isinstance(value, int):
return "int"
elif isinstance(value, float):
return "float"
elif isinstance(value, str):
return "str"
elif isinstance(value, bool):
return "bool"
elif isinstance(value, list):
return "list"
elif value is None:
return "None"
return str(type(value).__name__)
def visit(node):
if isinstance(node, list):
for n in node:
visit(n)
return None
elif hasattr(node, "__class__"):
cname = node.__class__.__name__
if cname == "Assign":
value = visit(node.expr)
var_name = node.name.name if hasattr(node.name, 'name') else node.name
type_info[var_name] = get_type(value)
symbol_table[var_name] = value
return value
elif cname == "Identifier":
var_name = node.name
if var_name not in symbol_table:
errors.append(f"❌ Undeclared variable: '{var_name}'")
return None
return symbol_table[var_name]
elif cname == "BinaryOp":
left = visit(node.left)
right = visit(node.right)
left_type = get_type(left)
right_type = get_type(right)
if left is not None and right is not None:
if node.op in ['+', '-', '*', '/', '%']:
if left_type not in ['int', 'float'] or right_type not in ['int', 'float']:
errors.append(f"❌ Type mismatch in arithmetic operation '{node.op}': {left_type} and {right_type}")
elif node.op in ['<', '>', '<=', '>=', '==', '!=']:
if left_type != right_type:
errors.append(f"❌ Type mismatch in comparison '{node.op}': {left_type} and {right_type}")
elif node.op in ['and', 'or']:
if left_type != 'bool' or right_type != 'bool':
errors.append(f"❌ Type mismatch in logical operation '{node.op}': {left_type} and {right_type}")
return None
elif cname == "Number":
return node.value
elif cname == "String":
return node.value
elif cname == "Boolean":
return node.value
elif cname == "Print":
expr = visit(node.expr)
if expr is not None:
type_info['print_expr'] = get_type(expr)
return None
elif cname == "IfElse":
cond = visit(node.condition)
if cond is not None and get_type(cond) != 'bool':
errors.append(f"❌ Condition must be a boolean, got {get_type(cond)}")
visit(node.if_body)
if node.else_body:
visit(node.else_body)
return None
elif cname == "WhileLoop":
cond = visit(node.condition)
if cond is not None and get_type(cond) != 'bool':
errors.append(f"❌ While loop condition must be a boolean, got {get_type(cond)}")
visit(node.body)
return None
elif cname == "ForLoop":
var_name = node.var.name if hasattr(node.var, 'name') else node.var
iterable = visit(node.iterable)
if iterable is not None:
iter_type = get_type(iterable)
if iter_type not in ['list', 'range']:
errors.append(f"❌ For loop iterable must be a list or range, got {iter_type}")
old_symbol_table = symbol_table.copy()
symbol_table[var_name] = None
visit(node.body)
symbol_table.clear()
symbol_table.update(old_symbol_table)
return None
elif cname == "FunctionDef":
func_name = node.name
symbol_table[func_name] = "function"
type_info[func_name] = "function"
old_symbol_table = symbol_table.copy()
for param in node.params:
symbol_table[param] = None
type_info[param] = "parameter"
visit(node.body)
symbol_table.clear()
symbol_table.update(old_symbol_table)
return None
elif cname == "FunctionCall":
func_name = node.name.name if hasattr(node.name, 'name') else node.name
if func_name not in symbol_table:
errors.append(f"❌ Undeclared function: '{func_name}'")
for arg in node.args:
visit(arg)
return None
elif cname == "ListNode":
elements = [visit(elem) for elem in node.elements]
return elements
elif cname == "IndexNode":
lst = visit(node.expr)
idx = visit(node.index)
if lst is not None and get_type(lst) != 'list':
errors.append(f"❌ Indexing requires a list, got {get_type(lst)}")
if idx is not None and get_type(idx) != 'int':
errors.append(f"❌ List index must be an integer, got {get_type(idx)}")
return None
elif cname == "StringMethod":
string_obj = visit(node.string_obj)
if string_obj is not None and get_type(string_obj) != 'str':
errors.append(f"❌ String method '{node.method}' called on non-string type: {get_type(string_obj)}")
for arg in getattr(node, 'args', []) or []:
visit(arg)
return None
elif cname == "RangeCall":
args = [node.start, node.stop, node.step]
for i, arg in enumerate(args):
val = visit(arg) if arg is not None else None
if val is not None and get_type(val) != 'int':
errors.append(f"❌ Range argument {i+1} must be an integer, got {get_type(val)}")
return None
elif cname == "Return":
value = visit(node.expr)
if value is not None:
type_info['return_value'] = get_type(value)
return None
elif cname == "TryExcept":
visit(node.try_body)
visit(node.except_body)
return None
elif cname == "LenFunction":
expr = visit(node.expr)
if expr is not None:
expr_type = get_type(expr)
if expr_type not in ['list', 'str']:
errors.append(f"❌ len() requires a list or string, got {expr_type}")
return None
elif cname == "UnaryOp":
expr = visit(node.expr)
if expr is not None:
expr_type = get_type(expr)
if node.op == '-' and expr_type not in ['int', 'float']:
errors.append(f"❌ Unary minus requires a number, got {expr_type}")
elif node.op == 'not' and expr_type != 'bool':
errors.append(f"❌ Logical not requires a boolean, got {expr_type}")
return None
return None
return None
visit(ast)
# Format the output
output = []
if errors:
output.append("❌ Semantic Errors Found:")
for error in errors:
output.append(f" {error}")
else:
output.append("✅ No semantic errors found!")
output.append("\nType Information:")
output.append("----------------")
for var, type_name in type_info.items():
output.append(f" {var}: {type_name}")
output.append("\nSymbol Table:")
output.append("-------------")
for var, value in symbol_table.items():
if value == "function":
output.append(f" {var}: function")
else:
output.append(f" {var}: {get_type(value)}")
return len(errors) == 0, "\n".join(output)
# Define the original generate_icg function
def generate_icg(ast):
code_lines = []
temp_counter = [0]
label_counter = [0]
def new_temp():
temp_counter[0] += 1
return f"t{temp_counter[0]}"
def new_label():
label_counter[0] += 1
return f"L{label_counter[0]}"
def visit(node):
if isinstance(node, list):
for n in node:
visit(n)
return None
elif hasattr(node, "__class__"):
cname = node.__class__.__name__
if cname == "Assign":
rhs = visit(node.expr)
code_lines.append(f"{node.name} = {rhs}")
return node.name
elif cname == "Number":
temp = new_temp()
code_lines.append(f"{temp} = {node.value}")
return temp
elif cname == "String":
temp = new_temp()
code_lines.append(f"{temp} = '{node.value}'")
return temp
elif cname == "Boolean":
temp = new_temp()
code_lines.append(f"{temp} = {node.value}")
return temp
elif cname == "Identifier":
temp = new_temp()
code_lines.append(f"{temp} = {node.name}")
return temp
elif cname == "BinaryOp":
left = visit(node.left)
right = visit(node.right)
temp = new_temp()
code_lines.append(f"{temp} = {left} {node.op} {right}")
return temp
elif cname == "UnaryOp":
expr = visit(node.expr)
temp = new_temp()
code_lines.append(f"{temp} = {node.op} {expr}")
return temp
elif cname == "Print":
val = visit(node.expr)
code_lines.append(f"print {val}")
return None
elif cname == "IfElse":
cond = visit(node.condition)
else_label = new_label()
end_label = new_label()
code_lines.append(f"if {cond} == False goto {else_label}")
for stmt in node.if_body:
visit(stmt)
code_lines.append(f"goto {end_label}")
code_lines.append(f"{else_label}:")
if node.else_body:
for stmt in node.else_body:
visit(stmt)
code_lines.append(f"{end_label}:")
return None
elif cname == "WhileLoop":
start_label = new_label()
end_label = new_label()
code_lines.append(f"{start_label}:")
cond = visit(node.condition)
code_lines.append(f"if {cond} == False goto {end_label}")
for stmt in node.body:
visit(stmt)
code_lines.append(f"goto {start_label}")
code_lines.append(f"{end_label}:")
return None
elif cname == "ForLoop":
start_label = new_label()
end_label = new_label()
iter_var = new_temp()
# Initialize iterator
iter_expr = visit(node.iterable)
code_lines.append(f"{iter_var} = {iter_expr}")
code_lines.append(f"{start_label}:")
# Check if iteration is complete
code_lines.append(f"if {iter_var} == None goto {end_label}")
# Assign current value to loop variable
code_lines.append(f"{node.var} = {iter_var}")
# Execute loop body
for stmt in node.body:
visit(stmt)
# Move to next iteration
code_lines.append(f"goto {start_label}")
code_lines.append(f"{end_label}:")
return None
elif cname == "FunctionDef":
code_lines.append(f"function {node.name}:")
for param in node.params:
code_lines.append(f"param {param}")
for stmt in node.body:
visit(stmt)
return None
elif cname == "FunctionCall":
args = [visit(arg) for arg in node.args]
# Convert None to 'None' string to avoid join error
safe_args = [str(a) if a is not None else "None" for a in args]
temp = new_temp()
code_lines.append(f"{temp} = call {node.name}({', '.join(safe_args)})")
return temp
elif cname == "ListNode":
temp = new_temp()
code_lines.append(f"{temp} = []")
for elem in node.elements:
elem_temp = visit(elem)
code_lines.append(f"{temp}.append({elem_temp})")
return temp
elif cname == "IndexNode":
lst = visit(node.expr)
idx = visit(node.index)
temp = new_temp()
code_lines.append(f"{temp} = {lst}[{idx}]")
return temp
elif cname == "ListAssign":
lst = visit(node.expr)
idx = visit(node.index)
val = visit(node.value)
code_lines.append(f"{lst}[{idx}] = {val}")
return None
elif cname == "Return":
val = visit(node.expr)
code_lines.append(f"return {val}")
return None
elif cname == "Break":
code_lines.append("break")
return None
elif cname == "Continue":
code_lines.append("continue")
return None
elif cname == "TryExcept":
try_label = new_label()
except_label = new_label()
end_label = new_label()
code_lines.append(f"{try_label}:")
for stmt in node.try_block:
visit(stmt)
code_lines.append(f"goto {end_label}")
code_lines.append(f"{except_label}:")
for stmt in node.except_block:
visit(stmt)
code_lines.append(f"{end_label}:")
return None
elif cname == "StringMethod":
string_obj = visit(node.string_obj)
temp = new_temp()
if node.method == "upper":
code_lines.append(f"{temp} = {string_obj}.upper()")
elif node.method == "lower":
code_lines.append(f"{temp} = {string_obj}.lower()")
elif node.method == "strip":
code_lines.append(f"{temp} = {string_obj}.strip()")
elif node.method == "replace":
args = [visit(arg) for arg in node.args]
code_lines.append(f"{temp} = {string_obj}.replace({args[0]}, {args[1]})")
return temp
elif cname == "LenFunction":
expr = visit(node.expr)
temp = new_temp()
code_lines.append(f"{temp} = len({expr})")
return temp
elif cname == "RangeCall":
start = visit(node.start) if node.start else "0"
stop = visit(node.stop) if node.stop else "None"
step = visit(node.step) if node.step else "1"
temp = new_temp()
code_lines.append(f"{temp} = range({start}, {stop}, {step})")
return temp
return None
return None
visit(ast)
# Format the output
output = []
output.append("Intermediate Code (Three-Address Code):")
output.append("=====================================")
output.append("")
for i, line in enumerate(code_lines, 1):
output.append(f"{i:3d} | {line}")
output.append("\nLegend:")
output.append("-------")
output.append("tN : Temporary variable")
output.append("LN : Label")
output.append("goto : Jump instruction")
output.append("call : Function call")
output.append("param : Function parameter")
return "\n".join(output)
# Now patch semantic_analysis and generate_icg
old_semantic_analysis = semantic_analysis
def semantic_analysis(ast):
ast = ensure_list(ast)
return old_semantic_analysis(ast)
old_generate_icg = generate_icg
def generate_icg(ast):
ast = ensure_list(ast)
return old_generate_icg(ast)
def update_phase_output(phase_name, content):
text_widget = phase_sections[phase_name]["text"]
text_widget.config(state=tk.NORMAL)
text_widget.delete("1.0", tk.END)
text_widget.insert("1.0", content)
text_widget.config(state=tk.DISABLED)
def optimize_code_icg(icg_code):
if not icg_code or icg_code == "<no intermediate code generated>":
return "⚠️ No intermediate code to optimize."
lines = icg_code.split('\n')
optimized_lines = []
optimizations = []
# Skip header and legend
start_idx = 0
for i, line in enumerate(lines):
if line.strip() and not line.startswith('Legend:'):
start_idx = i
break
# Process each line
i = start_idx
while i < len(lines):
line = lines[i].strip()
if not line or line.startswith('Legend:'):
break
# Extract the actual code part (after line number)
code = line.split('|', 1)[1].strip() if '|' in line else line
# Constant Folding
if '=' in code and any(op in code for op in ['+', '-', '*', '/']):
try:
# Try to evaluate constant expressions
left, right = code.split('=', 1)
left = left.strip()
right = right.strip()
# Check if right side is a constant expression
if all(c.isdigit() or c in '+-*/() ' for c in right):
result = eval(right)
optimized_lines.append(f"{left} = {result}")
optimizations.append(f"Constant folding: {right} → {result}")
i += 1
continue
except:
pass
# Copy Propagation
if '=' in code and not any(op in code for op in ['+', '-', '*', '/']):
left, right = code.split('=', 1)
left = left.strip()
right = right.strip()
# Check if right side is just a variable
if right.isidentifier():
# Look ahead for uses of left
for j in range(i + 1, len(lines)):
next_line = lines[j].split('|', 1)[1].strip() if '|' in lines[j] else lines[j]
if left in next_line and '=' not in next_line:
optimized_lines.append(f"# {code} # Copy propagated")
optimizations.append(f"Copy propagation: {left} → {right}")
i += 1
break
else:
optimized_lines.append(code)
i += 1
continue
# Common Subexpression Elimination
if i > 0 and i < len(lines) - 1:
prev_code = lines[i-1].split('|', 1)[1].strip() if '|' in lines[i-1] else lines[i-1]
next_code = lines[i+1].split('|', 1)[1].strip() if '|' in lines[i+1] else lines[i+1]
if '=' in code and '=' in prev_code and '=' in next_code:
prev_left, prev_right = prev_code.split('=', 1)
curr_left, curr_right = code.split('=', 1)
next_left, next_right = next_code.split('=', 1)
if prev_right.strip() == curr_right.strip():
optimized_lines.append(f"# {code} # Common subexpression eliminated")
optimizations.append(f"Common subexpression elimination: {curr_right} → {prev_left}")
i += 1
continue
# Loop Optimization
if 'goto' in code and 'L' in code:
# Check if this is a loop
if i > 0 and 'if' in lines[i-1]:
# Try to move loop-invariant code outside
loop_start = i
while i < len(lines) and 'goto' not in lines[i]:
i += 1
loop_end = i
# Check for loop-invariant code
for j in range(loop_start, loop_end):
loop_line = lines[j].split('|', 1)[1].strip() if '|' in lines[j] else lines[j]
if '=' in loop_line and not any(var in loop_line for var in ['i', 'j', 'k']):
optimized_lines.append(f"# {loop_line} # Moved outside loop")
optimizations.append(f"Loop optimization: Moved invariant code outside loop")
continue
optimized_lines.append(loop_line)
i += 1
continue
# Dead Code Elimination
if '=' in code:
left = code.split('=', 1)[0].strip()
# Check if variable is used later
used = False
for j in range(i + 1, len(lines)):
next_line = lines[j].split('|', 1)[1].strip() if '|' in lines[j] else lines[j]
if left in next_line and '=' not in next_line:
used = True
break
if not used:
optimized_lines.append(f"# {code} # Dead code eliminated")
optimizations.append(f"Dead code elimination: {left} is never used")
i += 1
continue
optimized_lines.append(code)
i += 1
# Format the output
output = []
output.append("Code Optimization Analysis:")
output.append("==========================")
output.append("")
if optimizations:
output.append("Applied Optimizations:")
output.append("---------------------")
for opt in optimizations:
output.append(f"✓ {opt}")
output.append("")
output.append("Optimized Code:")
output.append("--------------")
for i, line in enumerate(optimized_lines, 1):
output.append(f"{i:3d} | {line}")
output.append("\nOptimization Summary:")
output.append("-------------------")
output.append(f"• Total optimizations applied: {len(optimizations)}")
output.append("• Types of optimizations:")
output.append(" - Constant folding")
output.append(" - Copy propagation")
output.append(" - Common subexpression elimination")
output.append(" - Loop optimization")