A code generator for Lotus

Generate a Lotus program to an assembly code.
This project will use the lexical analyzer, the parser, the type checker.


Description

The code generator shall read input from stdin, writes output to stdout, and writes errors to stderr. The frame of this program is shown in the following figure.


-- A program to sum 1 to n
int sum(int n)
{
    int s;

    s = 0;
    while (n > 0) {
        s = s + n;
        n = n - 1;
    }
    return s;
}

int main( )
{
    int n;
    int s;

    read n;
    if (n < 0) {
        write -1;
        exit;
    } else {
        s = sum(n);
    }
    write s;
    return 0;
}



The output for this sample

.text
sum:
    li $t0, 32
    sub $sp, $sp, $t0
    sw $ra, 12($sp)
    sw $fp, 8($sp)
    li $t0, 28
    add $fp, $sp, $t0
    li $t0, 0
    sw $t0, -24($fp)
L1:
    lw $t0, -12($fp)
    li $t1, 0
    bgt $t0, $t1, L3
    b L2
L3:
    lw $t0, -24($fp)
    lw $t1, -12($fp)
    add $t0, $t0, $t1
    sw $t0, -24($fp)
    lw $t0, -12($fp)
    li $t1, 1
    sub $t0, $t0, $t1
    sw $t0, -12($fp)
    b L1
L2:
    lw $t0, -24($fp)
    move $v0, $t0
    b __sum_EXIT
__sum_EXIT:
    lw $ra, 12($sp)
    lw $fp, 8($sp)
    li $t0, 32
    add $sp, $sp, $t0
    jr $ra
main:
    li $t0, 32
    sub $sp, $sp, $t0
    sw $ra, 12($sp)
    sw $fp, 8($sp)
    li $t0, 28
    add $fp, $sp, $t0
    li $v0, 5
    syscall
    sw $v0, -24($fp)
    lw $t0, -24($fp)
    li $t1, 0
    blt $t0, $t1, L4
    b L5
L4:
    li $t0, 1
    neg $t0, $t0
    move $a0, $t0
    li $v0, 1
    syscall
    li $v0, 10
    syscall
    b L6
L5:
    lw $t0, -24($fp)
    sw $t0, -16($sp)
    jal sum
    move $t0, $v0
    sw $t0, -28($fp)
L6:
    lw $t0, -28($fp)
    move $a0, $t0
    li $v0, 1
    syscall
    li $t0, 0
    move $v0, $t0
    b __main_EXIT
__main_EXIT:
    lw $ra, 12($sp)
    lw $fp, 8($sp)
    li $t0, 32
    add $sp, $sp, $t0
    jr $ra