This is one of my most favorite projects that I've done. A compiler made in class that targets the pl/0 educational programming language. Compiles down to a custom 'interpreted' assembly ran by a virtual machine (vm) made in class.
Constants can be declared but not reassigned.
const u = 5;
variables can be declared and reassigned and even assigned to each other.
var x, y;
y := 5;
y := 6;
x := 8;
x := y + 2;
Functions are declared by procedure and their name. They can be called later with the keyword "call"
procedure functionname;
...
;
call functionname
Functions can be called within themselves and all their variables and other information will persist on the call stack.
procedure recursiveFunction;
call recursiveFunction;
;
As always needed for documentation, comments.
/*this is a comment*/
begin
...
end.
- Compile the compiler.c and the vm.c program
$ gcc compiler.c -o compiler
$ gcc vm.c -o vm
- Run the compiler with the desired input file
$ ./compiler <input file>
- This will create a "tokens.txt" file and an "elf.text" file
- Run the vm executable along with the elf.text file that was created earlier
$ ./vm elf.text
And you should get a runnable program that shows each instruction executed and a cool representation of the call stack, and other machine code info.
Showing the assembly code generated by the compiler
And a short example of the code trace when ran by the Virtual Machine