Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
229 lines (189 loc) · 7.02 KB
/
Copy pathmain.py
File metadata and controls
229 lines (189 loc) · 7.02 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
"""
Main program for testing the Lexical Analyzer, Syntax Analyzer, and ICG
"""
import sys
import traceback
# Import your existing modules
from lexer import Lexer
from compiler_core import TokenType, ParseError
from parser import Parser
from ll1_parser import LL1Parser, LL1_Grammar
# Import the newly created ICG module
from icg import IntermediateCodeGenerator
def print_ast(node, indent="", is_last=True):
"""Recursively prints the custom AST Nodes in a readable tree format."""
marker = "└── " if is_last else "├── "
# Base case: if it's a Token (leaf node without children)
if not hasattr(node, "children"):
type_val = getattr(node, "type", type(node).__name__)
val = getattr(node, "value", str(node))
print(f"{indent}{marker}Token({type_val}: {val})")
return
# Recursive case: It's an AST Node
print(f"{indent}{marker}{node.type}")
# Calculate indentation for children
next_indent = indent + (" " if is_last else "│ ")
children = node.children or []
# Recursively print all children
for i, child in enumerate(children):
print_ast(child, next_indent, i == len(children) - 1)
def display_menu():
print("\n" + "="*80)
print("COMPILER CONSTRUCTION PIPELINE".center(80))
print("="*80)
print("1. Read source code from a file")
print("2. Enter source code manually")
print("3. Run default example program")
print("4. Exit")
print("="*80)
def input_from_file():
filename = input("Enter the filename (e.g., test.txt): ").strip()
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"[ERROR] File '{filename}' not found.")
return None
except Exception as e:
print(f"[ERROR] Could not read file: {e}")
return None
def input_manually():
print("Enter your source code below. Type 'END' on a new line when finished:")
lines = []
while True:
line = input()
if line.strip() == 'END':
break
lines.append(line)
return '\n'.join(lines)
def example_program():
# A robust example covering arithmetic, conditions, and loops for the ICG
return """
int a;
int b;
int c;
a = 10;
b = 20;
c = a + b * 2;
if (c > 30) {
print(c);
} else {
c = c - 1;
}
while (a < b) {
a = a + 1;
}
"""
def analyze_code(source_code):
"""
Core pipeline: Lexer -> Parser (AST) -> ICG
"""
print("\n" + "="*80)
print("PHASE 1: LEXICAL ANALYSIS")
print("="*80)
lexer = Lexer(source_code)
tokens = lexer.tokenize()
lexer.print_tokens()
if lexer.errors:
lexer.print_errors()
print("\n[COMPILER HALTED] Lexical errors found. Cannot proceed to parsing.")
return
print("\n" + "="*80)
print("PHASE 2: SYNTAX & SEMANTIC ANALYSIS (Parser Output)")
print("="*80)
ast_root = None
try:
# We pass the tokens generated by the lexer into your parser
parser = Parser(tokens)
# Parse the program and build the AST
ast_root = parser.parse_program()
print("\n[SUCCESS] Abstract Syntax Tree (AST) built successfully.\n")
# --- PRINT 1: The Derivation Log (Rules Applied) ---
print("--- Grammar Derivations Applied ---")
if hasattr(parser, 'derivation_log') and parser.derivation_log:
for step, rule in enumerate(parser.derivation_log, 1):
print(f"Step {step:02d}: {rule}")
else:
print("No derivations logged.")
# --- PRINT 2: The Abstract Syntax Tree (AST) ---
print("\n--- Abstract Syntax Tree Structure ---")
# Save AST to file to avoid terminal truncation
import io
import sys
old_stdout = sys.stdout
sys.stdout = buffer = io.StringIO()
print_ast(ast_root, indent="", is_last=True)
ast_output = buffer.getvalue()
sys.stdout = old_stdout
with open("ast_structure.txt", "w", encoding="utf-8") as f:
f.write("Abstract Syntax Tree Structure:\n\n")
f.write(ast_output)
print("AST structure saved to 'ast_structure.txt'")
print("First few lines:")
lines = ast_output.split('\n')[:10]
for line in lines:
print(line)
# --- PRINT 3: LL(1) Parser Table ---
print("\n--- LL(1) Parser Table ---")
ll1_grammar = LL1_Grammar()
ll1_parser = LL1Parser(tokens)
table = ll1_parser.build_ll1_table(ll1_grammar.productions, "Program")
# Write table to file instead of printing to avoid terminal truncation
with open("ll1_table.txt", "w", encoding="utf-8") as f:
f.write("PARSE_TABLE:\n\n")
for nt in ll1_grammar.productions:
for t in ll1_grammar.terminals | {"EOF"}:
if (nt, t) in table:
prod = table[(nt, t)]
rhs = ", ".join(f'"{sym}"' for sym in prod)
f.write(f' ("{nt}", "{t}"): [{rhs}],\n')
f.write("\n")
print("LL(1) parsing table saved to 'll1_table.txt'")
print("First few entries:")
count = 0
for nt in ll1_grammar.productions:
for t in ll1_grammar.terminals | {"EOF"}:
if (nt, t) in table and count < 10:
prod = table[(nt, t)]
rhs = ", ".join(f'"{sym}"' for sym in prod)
print(f' ("{nt}", "{t}"): [{rhs}]')
count += 1
except ParseError as e:
print(f"\n[ERROR] Syntax/Semantic Analysis failed:\n{e}")
print("\n[COMPILER HALTED] Cannot proceed to ICG due to syntax/semantic errors.")
return
except Exception as e:
print(f"\n[CRITICAL ERROR] Unexpected error during parsing:\n{e}")
traceback.print_exc()
return
# Phase 3: Intermediate Code Generation
if ast_root:
icg = IntermediateCodeGenerator()
icg.generate(ast_root)
print("\n[COMPILER SUCCESS] All phases executed properly.")
def main():
while True:
display_menu()
choice = input("Enter your choice (1-4): ").strip()
if choice == "1":
source_code = input_from_file()
if source_code:
analyze_code(source_code)
elif choice == "2":
source_code = input_manually()
if source_code:
analyze_code(source_code)
elif choice == "3":
source_code = example_program()
print("\nRunning example program:")
print("-" * 80)
print(source_code.strip())
print("-" * 80)
analyze_code(source_code)
elif choice == "4":
print("Exiting compiler. Goodbye!")
sys.exit(0)
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()