# Pass 1: Symbol Table and Address Calculation
def pass1(assembly_code):
symbol_table = {}
address = 0
intermediate_code = []
for line in assembly_code:
tokens = line.split()
if tokens[0][-1] == ':': # If line starts with a label
label = tokens[0][:-1] # Remove the colon
symbol_table[label] = address
tokens = tokens[1:] # Remove the label from the instruction
if tokens: # Only process non-empty lines
intermediate_code.append((address, tokens))
address += 1 # Increment address for each instruction
return symbol_table, intermediate_code
# Pass 2: Replace Labels with Addresses and Generate Machine Code
def pass2(symbol_table, intermediate_code):
machine_code = []
for address, instruction in intermediate_code:
# Translate the instruction to machine code (simple example)
machine_instr = []
for token in instruction:
if token in symbol_table: # Replace labels with addresses
machine_instr.append(str(symbol_table[token]))
else:
machine_instr.append(token)
machine_code.append((address, " ".join(machine_instr)))
return machine_code
# Example Assembly Code
assembly_code = [
"START: MOV A, B",
" ADD A, C",
" MOV D, A",
" HALT"
]
# Pass 1: Create Symbol Table and Intermediate Code
symbol_table, intermediate_code = pass1(assembly_code)
# Pass 2: Generate Machine Code
machine_code = pass2(symbol_table, intermediate_code)
# Output the results
print("Symbol Table:")
for label, address in symbol_table.items():
print(f"{label}: {address}")
print("\nIntermediate Code:")
for address, instruction in intermediate_code:
print(f"Address {address}: {' '.join(instruction)}")
print("\nMachine Code:")
for address, code in machine_code:
print(f"Address {address}: {code}")