-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
354 lines (277 loc) · 10.6 KB
/
main.py
File metadata and controls
354 lines (277 loc) · 10.6 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
"""
MAIN COMPILER DRIVER
This is the complete compiler that ties all phases together.
Compiler Pipeline:
==================
Source Code (TinyLang)
↓
[1] LEXER → Tokens
↓
[2] PARSER → AST
↓
[3] SEMANTIC ANALYZER → Validated AST
↓
[4] CODE GENERATOR → Three Address Code
↓
[5] INTERPRETER → Execution & Output
Each phase is clearly separated and can be studied independently.
"""
from lexer import Lexer
from ast_parser import Parser, print_ast
from semantic import SemanticAnalyzer
from intermediate import IntermediateCodeGenerator, print_tac
from interpreter import Interpreter
class Compiler:
"""
Complete Compiler for TinyLang
This class orchestrates all compiler phases.
"""
def __init__(self, source_code, verbose=True):
"""
Initialize compiler
Args:
source_code: The program to compile
verbose: If True, print detailed output from each phase
"""
self.source_code = source_code
self.verbose = verbose
# Results from each phase
self.tokens = None
self.ast = None
self.tac = None
def compile_and_run(self):
"""
Run all compiler phases and execute the program
Returns:
True if compilation and execution succeeded
"""
try:
# Display source code
self.print_header("SOURCE CODE")
print(self.source_code)
# Phase 1: Lexical Analysis
if not self.phase1_lexical_analysis():
return False
# Phase 2: Syntax Analysis (Parsing)
if not self.phase2_parsing():
return False
# Phase 3: Semantic Analysis
if not self.phase3_semantic_analysis():
return False
# Phase 4: Intermediate Code Generation
if not self.phase4_code_generation():
return False
# Phase 5: Execution
if not self.phase5_execution():
return False
# Success!
self.print_header("COMPILATION SUCCESSFUL! 🎉")
return True
except Exception as e:
print(f"\n❌ COMPILATION FAILED!")
print(f"Error: {e}")
return False
def print_header(self, title):
"""Print a formatted section header"""
print("\n" + "=" * 70)
print(f" {title}")
print("=" * 70)
def phase1_lexical_analysis(self):
"""
Phase 1: Lexical Analysis (Tokenization)
Converts source code into tokens.
"""
self.print_header("PHASE 1: LEXICAL ANALYSIS")
try:
lexer = Lexer(self.source_code)
self.tokens = lexer.tokenize()
if self.verbose:
print("\n🔤 Token Stream:")
print("-" * 70)
for i, token in enumerate(self.tokens):
print(f" {i:3d}: {token}")
print(f"\n✅ Lexical Analysis Complete: {len(self.tokens)} tokens generated")
return True
except Exception as e:
print(f"❌ Lexical Analysis Failed: {e}")
return False
def phase2_parsing(self):
"""
Phase 2: Syntax Analysis (Parsing)
Builds an Abstract Syntax Tree from tokens.
"""
self.print_header("PHASE 2: SYNTAX ANALYSIS (PARSING)")
try:
parser = Parser(self.tokens)
self.ast = parser.parse()
if self.verbose:
print("\n🌳 Abstract Syntax Tree (AST):")
print("-" * 70)
print_ast(self.ast)
print(f"\n✅ Parsing Complete: AST constructed")
return True
except Exception as e:
print(f"❌ Parsing Failed: {e}")
return False
def phase3_semantic_analysis(self):
"""
Phase 3: Semantic Analysis
Checks for semantic errors (undefined variables, type errors, etc.)
"""
self.print_header("PHASE 3: SEMANTIC ANALYSIS")
try:
analyzer = SemanticAnalyzer()
# Suppress detailed output if not verbose
if not self.verbose:
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = StringIO()
is_valid = analyzer.analyze(self.ast)
if not self.verbose:
sys.stdout = old_stdout
if not is_valid:
print(f"❌ Semantic Analysis Failed: {len(analyzer.errors)} error(s) found")
for error in analyzer.errors:
print(f" - {error}")
return False
if self.verbose:
print("\n" + str(analyzer.symbol_table))
print(f"\n✅ Semantic Analysis Complete: No errors found")
return True
except Exception as e:
print(f"❌ Semantic Analysis Failed: {e}")
return False
def phase4_code_generation(self):
"""
Phase 4: Intermediate Code Generation
Generates Three Address Code from AST.
"""
self.print_header("PHASE 4: INTERMEDIATE CODE GENERATION")
try:
generator = IntermediateCodeGenerator()
# Suppress detailed output if not verbose
if not self.verbose:
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = StringIO()
self.tac = generator.generate(self.ast)
if not self.verbose:
sys.stdout = old_stdout
if self.verbose:
print_tac(self.tac)
else:
print(f"\n✅ Code Generation Complete: {len(self.tac)} TAC instructions")
return True
except Exception as e:
print(f"❌ Code Generation Failed: {e}")
return False
def phase5_execution(self):
"""
Phase 5: Execution (Interpretation)
Executes the Three Address Code.
"""
self.print_header("PHASE 5: EXECUTION")
try:
interpreter = Interpreter(self.tac)
# Suppress detailed output if not verbose
if not self.verbose:
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = StringIO()
interpreter.run()
if not self.verbose:
# Get the output that was printed
output = sys.stdout.getvalue()
sys.stdout = old_stdout
# Extract and print only OUTPUT lines
for line in output.split('\n'):
if line.startswith('OUTPUT:'):
print(line)
print(f"\n✅ Execution Complete")
return True
except Exception as e:
print(f"❌ Execution Failed: {e}")
return False
def main():
"""
Main entry point
Demonstrates the compiler with example programs.
"""
print("╔" + "═" * 68 + "╗")
print("║" + " " * 68 + "║")
print("║" + " 🎓 EDUCATIONAL TOY COMPILER FOR TINYLANG".center(68) + "║")
print("║" + " A Complete Compiler Implementation in Python".center(68) + "║")
print("║" + " " * 68 + "║")
print("╚" + "═" * 68 + "╝")
# Example 1: Basic arithmetic
print("\n\n" + "█" * 70)
print(" EXAMPLE 1: Basic Arithmetic")
print("█" * 70)
program1 = """
x = 5;
y = x + 10;
print(y);
"""
compiler1 = Compiler(program1, verbose=True)
compiler1.compile_and_run()
# Example 2: More complex expressions
print("\n\n" + "█" * 70)
print(" EXAMPLE 2: Complex Expressions")
print("█" * 70)
program2 = """
a = 10;
b = 20;
c = a + b * 2;
d = (a + b) * 2;
print(c);
print(d);
"""
compiler2 = Compiler(program2, verbose=False)
compiler2.compile_and_run()
# Example 3: Error handling (semantic error)
print("\n\n" + "█" * 70)
print(" EXAMPLE 3: Error Handling (Undefined Variable)")
print("█" * 70)
program3 = """
x = 5;
y = z + 10;
print(y);
"""
compiler3 = Compiler(program3, verbose=False)
compiler3.compile_and_run()
# Final message
print("\n\n" + "╔" + "═" * 68 + "╗")
print("║" + " " * 68 + "║")
print("║" + " 🎉 COMPILER DEMONSTRATION COMPLETE!".center(68) + "║")
print("║" + " " * 68 + "║")
print("║" + " You now understand how compilers work!".center(68) + "║")
print("║" + " " * 68 + "║")
print("║" + " Key Takeaways:".center(68) + "║")
print("║" + " • Lexer: Breaks code into tokens".center(68) + "║")
print("║" + " • Parser: Builds syntax tree (AST)".center(68) + "║")
print("║" + " • Semantic Analyzer: Checks meaning".center(68) + "║")
print("║" + " • Code Generator: Creates intermediate code".center(68) + "║")
print("║" + " • Interpreter: Executes the code".center(68) + "║")
print("║" + " " * 68 + "║")
print("║" + " Every real compiler (GCC, Clang, javac) follows".center(68) + "║")
print("║" + " these same fundamental phases!".center(68) + "║")
print("║" + " " * 68 + "║")
print("╚" + "═" * 68 + "╝")
print("\n📚 Next Steps:")
print(" 1. Modify the example programs and see what happens")
print(" 2. Add new operators (%, ==, !=, <, >)")
print(" 3. Add control flow (if statements, while loops)")
print(" 4. Add functions")
print(" 5. Generate actual assembly code instead of interpreting")
print("\n🔗 Each phase is in a separate file - study them one by one!")
print(" • lexer.py - Tokenization")
print(" • parser.py - AST construction")
print(" • semantic.py - Semantic checking")
print(" • intermediate.py - TAC generation")
print(" • interpreter.py - Execution")
print()
if __name__ == "__main__":
main()