and test_code_3_misp_sim.asm
.data
num1: .word 8
num2: .word 3
.text
lw a0, num1 # Load the value of num1 into a0
lw a1, num2 # Load the value of num2 into a1
addi a2,a0, 5 # Add 5 to the value in a0andstoreina2
beq a0,a1, case_equal # Branch if num1 equals num2
sub t0,a0, a1 # Subtract num2 from num1, result in t0
j end_program # Jump to end_program
case_equal:
add t0,a0, a1 # If equal, add num1 and num2, result in t0
end_program:
Traceback (most recent call last):
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 371, in
main()
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 362, in main
instructions, data_section = compiler.compile_file(asm_file)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 60, in compile_file
compiled_instructions = self._second_pass(lines)
^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 124, in _second_pass
binary = self._compile_instruction(stripped, current_address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 145, in _compile_instruction
return self._encode_i_type(op, parts[1:], address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\auspi\OneDrive\Desktop\CArch_Assignment_5\B22CS004._B22CS087.py", line 165, in _encode_i_type
rt, expr = operands
^^^^^^^^
ValueError: too many values to unpack (expected 2)
The error you're encountering:
code
ValueError: too many values to unpack (expected 2)
indicates that the program is attempting to unpack more values than expected. Specifically, the _encode_i_type method expects a certain number of operands based on the instruction type, but it's receiving more operands than anticipated.
Root Cause
The primary issue stems from how the assembly instructions are being parsed. Here's a breakdown of what's happening:
Inline Comments Not Stripped Properly:
Your assembly code contains inline comments, for example:
assembly
lw $a0, num1 # Load the value of num1 into $a0
The current implementation uses stripped = line.strip() to process each line. However, this does not remove the inline comments, resulting in:
When _encode_i_type tries to unpack operands for lw (which expects 2 operands), it encounters additional tokens from the comment, leading to the ValueError.
Solution
To resolve this, you need to remove the comments before processing each instruction line. This ensures that only the relevant parts of the instruction are parsed.
Here's how you can modify your MIPSCompiler class to handle this:
Strip Inline Comments Before Parsing:
Update the _compile_instruction method to remove anything after a # symbol, which denotes a comment in MIPS assembly.
python
def _compile_instruction(self, instruction, address):
"""Compile a single instruction line into binary."""
# Remove inline comments
instruction = instruction.split('#')[0].strip()
parts = instruction.replace(',', '').split()
if not parts:
return None
op = parts[0].lower()
if op in self.opcodes['R']:
return self._encode_r_type(op, parts[1:])
elif op in self.opcodes['I']:
return self._encode_i_type(op, parts[1:], address)
elif op in self.opcodes['J']:
return self._encode_j_type(op, parts[1:])
return None
Alternatively, Strip Comments in the Second Pass:
If you prefer to handle comment stripping at an earlier stage, modify the _second_pass method to remove comments before passing the line to _compile_instruction.
python
def _second_pass(self, lines):
"""Second pass to compile text instructions."""
compiled = []
current_address = self.text_start
section = None
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith('#'):
continue
if stripped.startswith('.data'):
section = 'data'
continue
elif stripped.startswith('.text'):
section = 'text'
continue
if section == 'text':
if ':' in stripped:
continue # Labels are already processed in the first pass
# Remove inline comments
instruction = stripped.split('#')[0].strip()
binary = self._compile_instruction(instruction, current_address)
if binary:
compiled.append({
'binary': binary,
'original': stripped,
'address': f"{current_address:08x}"
})
current_address += 4
return compiled
Ensure Labels Are Handled Correctly:
Make sure that label lines (like case_equal: and end_program:) are correctly identified and skipped during the second pass.
Final Modified Code Snippet
Here's the updated MIPSCompiler class with the necessary changes:
python
Additional Recommendations
Consistent Comment Stripping:
Ensure that all methods handling instructions strip comments appropriately to avoid similar issues in the future.
Robust Parsing:
Consider implementing more robust parsing mechanisms, such as using regular expressions, to handle various edge cases in assembly code.
Error Handling:
Enhance error messages to include line numbers or the problematic instruction to make debugging easier.
Testing:
After implementing the changes, test the compiler with multiple assembly files containing different instruction types and comment placements to ensure stability.
Final Assembly File
After making the changes, your assembly file (test_code_3_misp_sim.asm) should work correctly:
assembly
.data
num1: .word 8
num2: .word 3
.text
lw $a0, num1 # Load the value of num1 into $a0
lw $a1, num2 # Load the value of num2 into $a1
addi $a2, $a0, 5 # Add 5 to the value in $a0 and store in $a2
beq $a0, $a1, case_equal # Branch if num1 equals num2
sub $t0, $a0, $a1 # Subtract num2 from num1, result in $t0
j end_program # Jump to end_program
case_equal:
add $t0, $a0, $a1 # If equal, add num1 and num2, result in $t0
end_program:
Conclusion
By ensuring that inline comments are properly stripped before parsing instructions, you can prevent the ValueError and allow your MIPS compiler and simulator to function as expected. Implementing robust comment handling is crucial for accurately interpreting assembly code.