lcompilers / lpython

Python compiler
https://lpython.org/
Other
1.5k stars 158 forks source link

[Bug] All global variable assignments should not go to `__main__global_init` #2573

Closed Vipul-Cariappa closed 4 months ago

Vipul-Cariappa commented 7 months ago

I came across this bug while trying to debug #2457.

Look at the code and output of the two cases

Code:

l: list[i32] = [1, 2, 3, 4]
print("Before Pop:", l)
x: i32 = l.pop()
print("After Pop:", l)
print("Poped Element: ", x)

Output:

Before Pop: [1, 2, 3]
After Pop: [1, 2, 3]
Poped Element:  4

Code:

l: list[i32] = [1, 2, 3, 4]
print("Before Pop:", l)
l.pop()
print("After Pop:", l)

Output:

Before Pop: [1, 2, 3, 4]
After Pop: [1, 2, 3]

This is happening because the line x: i32 = l.pop() is compiled into the __main__global_init function, but it should actually be compiled into __main__global_stmts. Because __main__global_init is called before __main__global_stmts.