Pass 2 code
def Pass2(assembly_code, SymbolTable):
# Initialize an empty list for the machine code output
machine_code = []
# Iterate through each line of the assembly code (Intermediate Representation)
for line in assembly_code:
# Remove any leading/trailing whitespaces
line = line.strip()
# Handle label resolutions for instructions
if ":" in line: # It's a label (skip it in code generation)
line = line.split(":")[1].strip()
# Check if the line is an instruction (e.g., ADD, LDR, MOV, etc.)
if line.startswith("LDR") or line.startswith("ADD") or line.startswith("MOV"):
# Extract the instruction and operands (e.g., "LDR R1, =num1")
parts = line.split() # Split by space to separate instruction and operands instruction = parts[0]
operands = part s[1:]
# Process operands to resolve labels
for i in range(len(operands)):
operand = operands[i]
if operand.startswith("="): # It's a label reference (e.g., "=num1")
label = operand[1:] # Strip the '=' sign to get the label (e.g., "num1")
if label in SymbolTable: # If the label exists in the Symbol Table
# Replace the label with its corresponding address
operands[i] = hex(SymbolTable[label]) # Use hex address from Symbol Table
else:
raise ValueError(f"Label {label} not found in Symbol Table.")
# Translate the instruction into machine code (this is a simplified example)
# The translation process can be more complex based on the instruction set architecture
if instruction == "LDR":
# Example: translating LDR R1, =num1 to a machine code instruction
# For simplicity, assume we're directly generating a machine code byte sequence (this is highly simplified)
machine_code.append(f"LDR {operands[0]}, {operands[1]}") # For demonstration
elif instruction == "ADD":
# Similar translation for ADD
machine_code.append(f"ADD {operands[0]}, {operands[1]}, {operands[2]}")
elif instruction == "MOV":
# Translate MOV instruction
machine_code.append(f"MOV {operands[0]}, {operands[1]}")
# Add more cases for different instructions as needed...
# Return the list of machine code instructions
return machine_code