This project implements the code generation phase of a Badlang compiler. The compiler translates a Badlang program into MIPS assembly, which can be executed using SPIM or other MIPS simulators.
The goal of this project is to generate correct and executable assembly that fully implements the semantics of Badlang, including:
- Variables and assignments
- Arithmetic and boolean expressions
- If / while control flow
- Function definitions and calls
- Return statements
- Print statements
- Proper stack frame handling
Target architecture: MIPS Simulator used: SPIM (online or local)
The compiler outputs valid MIPS assembly that follows the required constraints:
-
All variables and temporaries live on the stack
-
Only registers
$t0and$t1are used for intermediate computation -
No variable named
band no function namedadd -
Code is generated in three passes (data, functions, main)
-
A newline is printed after every
printstatement -
Execution ends with an exit syscall
-
Function stack frames follow the convention:
- First block has offset
-(8 + params.size * 4) $fpis not updated inside nested blocks
- First block has offset
javac edu/wisc/Main.java
java edu.wisc.Main <source-file> [output-file]
- If
output-fileis omitted, the compiler writes assembly toout.s.
Open the generated .s file in SPIM (desktop or online):
- Load the file
- Press Run
- Verify the output matches the expected Badlang behavior
-
Each function creates a stack frame containing:
- saved
$fp - return address
$ra - function parameters
- local variables
- saved
-
All expressions load operands into
$t0and$t1only -
Results are immediately written back to the stack
if/elseandwhileare implemented using unique labels- Conditions evaluate to 0 or 1, consistent with Badlang boolean semantics
print outputs integers or booleans (as 0 or 1), followed by a newline.
I tested the compiler using an online SPIM environment:
- Generate MIPS code with the compiler
- Copy and paste the assembly into SPIM
- Run and compare output with the expected behavior of the original Badlang program
I verified all major language features:
- Arithmetic and boolean expressions
- Variable assignment and scopes
- Blocks
{} - If–else statements
- While loops
- Functions (parameters, return values, nested calls)
- Printing
- Programs using multiple functions
The tests/ folder contains at least 10 example Badlang programs, covering:
- Simple arithmetic
- Boolean logic
- Nested blocks
- If / if-else
- Loops
- Recursive function
- Function parameters and return
- Variable shadowing
- Mixed prints
- A full “all features” program