3 ms·
I did not have a compiler course at university but I talked on r/programminglanguages discord and eatonphil's discord and I learned how to create a simple expr
by samsquire 4y ago
I did not have a compiler course at university but I talked on r/programminglanguages discord and eatonphil's discord and I learned how to create a simple expression compiler in Python.
You can run the code here:
https://replit.com/@Chronological/Compiler3 https://replit.com/@Chronological/Compiler3
It's ~400 lines of code and it compiles the following AST
program = Main(
[
Assign("a", LiteralNumber(5)),
Assign("b", LiteralNumber(6)),
Println("Value is %d",
Mul(Add(Reference("a"), LiteralNumber(7)),
Add(LiteralNumber(8), Reference("b")))),
Println("Hello world %d", LiteralNumber(10))])
Or in other words, the following expression:
a = 5
b = 6
(a + 7) * (8 + b)
If you run
python3 main.py > assembly.S
gcc -o assembled assembly.S
./assembled
You should see
Value is 168Hello world 10
It's barebones but I think it's the basis for a compiler.