-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode_genration.py
More file actions
28 lines (25 loc) · 918 Bytes
/
Copy pathCode_genration.py
File metadata and controls
28 lines (25 loc) · 918 Bytes
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
class CodeGenerator:
def __init__(self, tac):
self.tac = tac
self.assembly = []
def generate(self):
for line in self.tac:
lhs, rhs = line.split("=")
lhs = lhs.strip()
rhs = rhs.strip()
tokens = rhs.split()
# Case 1: Direct assignment (x = 5, x = y)
if len(tokens) == 1:
if tokens[0].isdigit():
self.assembly.append(f"PUSH {tokens[0]}")
else:
self.assembly.append(f"LOAD {tokens[0]}")
self.assembly.append(f"STORE {lhs}")
# Case 2: Binary operation (t1 = a + b)
elif len(tokens) == 3:
a, op, b = tokens
# Load left operand
if a.isdigit():
self.assembly.append(f"PUSH {a}")
else:
self.assembly.ap