lcompilers / lpython

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

Freeing variables correctly through visit_Return #2550

Closed anutosh491 closed 7 months ago

anutosh491 commented 7 months ago

Fixes #2533

Currently on master as soon as we encountered the return node, we thought it was the end of the program and we could free out everything. But consider the following

from lpython import S
from sympy import Symbol, log

def mmrv(e: S, x: S) -> list[S]:
    print(e)
    print(x)
    if e == x:
        list1: list[S] = [x]
        return list1
    else:
        print(e)
        list2: list[S] = mmrv(x, x)
        return list2

def test_mrv():
    x: S = Symbol("x")
    ans3: list[S] = mmrv(log(x), x)
    ele2: S = ans3[0]
    print(ele2)

test_mrv()

Here we can't free the variable e till the function reaches an end (As it is being used in the 2nd if block). So as shown in the issue this leads to incorrect results

This is now fixed and we get the correct output

log(x)
x
log(x)
x
x
x
anutosh491 commented 7 months ago

Closing as #2569 is a better approach to address this issue