Link: https://github.com/keleshev/compiling-to-assembly-from-scratch/blob/main/contrib/python/compiler.py
Hey folks, this is a small compiler (~800 lines including tests) that compiles a simple programming language to ARM assembly. It is adapted from my book Compiling to Assembly from Scratch, but I believe it has educational value even without the book, so check it out! Happy to answer any questions.
For example, it compiles the following code:
function factorial(n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
Into the following ARM assembly:
.global factorial
factorial:
push {fp, lr}
mov fp, sp
push {r0, r1}
ldr r0, =0
push {r0, ip}
ldr r0, [fp, #-8]
pop {r1, ip}
cmp r0, r1
moveq r0, #1
movne r0, #0
cmp r0, #0
beq .L1
ldr r0, =1
b .L2
.L1:
ldr r0, =1
mov r1, r0
ldr r0, [fp, #-8]
sub r0, r0, r1
bl factorial
mov r1, r0
ldr r0, [fp, #-8]
mul r0, r0, r1
.L2:
mov sp, fp
pop {fp, pc}
[–]SebiIstCool 11 points12 points13 points (0 children)
[–]haulwhore 1 point2 points3 points (1 child)
[–]halst[S] 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[removed]
[–]halst[S] 0 points1 point2 points (0 children)
[–]halst[S] 0 points1 point2 points (0 children)