elikaski / BF-it

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

Fixed a bug related to scopes in for loops #59

Closed NeeEoo closed 3 years ago

elikaski commented 3 years ago

Can you please provide an example problematic code that this change fixes?

NeeEoo commented 3 years ago

examples/games/tetris.code

NeeEoo commented 3 years ago

Also your tic_tac_toe.code if you make the for loops use scopes.

NeeEoo commented 3 years ago

@elikaski The code is i commited is based on the code before the bracketless-if/for/while

elikaski commented 3 years ago

This reverts an optimization I introduced in commit 0d0bc88 It can be seen in the following example, when defining a lot of in-scope variables (or one big array):

int main() {
    for (int i = 0; i < 10; i++) {
        int arr[50];
    }
}

With the optimization, the generated code is 306 characters Without the optimization, the generated code is 410 characters (additional 50 "<" and 50 ">")

NeeEoo commented 3 years ago

The thing is that the variables overwrite stuff. Without the optimization my Tetris game works. It only happens in scoped for loops.

NeeEoo commented 3 years ago

I think it overwrites i so in some cases it will make the for loop skip stuff

NeeEoo commented 3 years ago

The optimization isn't a optimization.

if I change the code to this with the optimization active:

int main() {
    for (int i = 0; i < 10; i++) {
        int arr[50] = {1};
    }
}

It will never halt.

This is due to the i variable being overwritten by the array. i gets set to zero.

The code im using for example

int main() {
    for (int i = 0; i != 10; i++) {
        int arr[50] = {3, 4, 5};
    }
}

with the optimization:

loop counter=1560
ptr=2
{
   cell -48 = 3  |  arr[0]
   cell -47 = 4  |  arr[1]
   cell -46 = 5  |  arr[2]
   cell 1 = 0    |  i
   cell 2 = 0    |  unknown
   cell 3 = 0    |  unknown
}

without:

loop counter=1
ptr=52
{
   cell 1 = 1  |  i
   cell 2 = 3  |  arr[0]
   cell 3 = 4  |  arr[1]
   cell 4 = 5  |  arr[2]
}