elikaski / BF-it

A C-like language to Brainfuck compiler, written in Python
MIT License
120 stars 11 forks source link

Make the compiler smarter with variables #39

Open NeeEoo opened 3 years ago

NeeEoo commented 3 years ago

The code below takes 276 bytes.

int main() {
    int a = 54;
    int b = 4;

    while(b != 0) {
        a++;
        b--;
    }
}

bf code for a and b init:

>>>[-]>[-]++++++[-<+++++++++>]<><>[-]<<<[-]>>[>+<<<+>>-]>[<+>-]<><[-]++++><>[-]<<[-]>[>+<<+>-]>[<+>-]

The code below takes 548 bytes.

int main() {
    int a = 54;
    int b = 4;

    while(b != 0) {
        a++;
        b--;
    }

    int c;
    int d;
    int e;
    int f;
    int g;
    int h;
    int i;
    int j;
}

bf code for a and b init:

>>>>>>>>>>>[-]>[-]++++++[-<+++++++++>]<><>[-]<<<<<<<<<<<[-]>>>>>>>>>>[>+<<<<<<<<<<<+>>>>>>>>>>-]>[<+>-]<><[-]++++><>[-]<<<<<<<<<<[-]>>>>>>>>>[>+<<<<<<<<<<+>>>>>>>>>-]>[<+>-]

Currently, the compiler allocates every variable present in the scope. Which means if you only use a small quantity of variables in the beginning and more later it will take up a lot more code size.

What I was thinking is that what if the compiler allocated enough and then when more variables appears it shifts the temp variables to the right  So then when a is declared only that is allocated. Every other variable technically exists in temp until it's declared.

This might also fix #35 since we could check if it is already declared.