Akuli / jou

Yet another programming language
MIT License
11 stars 4 forks source link

Memory leak warning at compile time #396

Open Akuli opened 10 months ago

Akuli commented 10 months ago

It would be nice to get errors for a malloc() whose return value is never free()d. However, I don't want:

Jou should still feel like C. It would just emit warnings for some common memory management mistakes.

For example, consider:

def foo():
    for i = 0; i < 10; i++:
        f = fopen(...)
        ...do stuff...
    fclose(f)

The decision tree for this function is basically:

                                ,--------- ... ---------.
                                V                       |
,-------.     .-------.     .--------. yes     ,----------------.
| start | --> | i = 0 | --> | i < 10 | ------> | f = fopen(...) | 
`-------'     `-------'     `--------'         `----------------'    
                                |no   ,-----------.      ,-----.
                                `---> | fclose(f) | ---> | end |
                                      `-----------'      `-----'

If the compiler knows that fopen(...) returns something that needs cleanup, and fclose(f) does cleanup to f, it could deduce that f may already contain something worth cleaning up when we get to f = fopen(...). It could then generate a warning that looks something like this:

compiler warning for file "foo.py", line 3: old value of variable 'f' should be cleaned up to avoid memory leaks

IMO we shouldn't distinguish various different kinds of things to be cleaned up. It is rare to accidentally use free() on a pointer that came from fopen(). It is much more common to forget the cleanup entirely or do it twice.

littlewhitecloud commented 9 months ago

Good idea, but I still feel like we should do a bit of garbage collection, at least with free() when the user has used malloc() and the recycling conditions are met.

Akuli commented 9 months ago

Once again, I don't want to add more magic to Jou. I want it to be a simple language that doesn't hide things from you. IMO such language shouldn't magically clean up your garbage.

That said, I believe that with good warnings, garbage collection will be only a very small inconvenience.

Moosems commented 8 months ago

And if the compiler is mistaken in some cases, there should be a way to notify it :).

Akuli commented 8 months ago

Undefined variables are a bit similar. There are currently two warnings:

If you get a "may be undefined" warning, you should probably rewrite that part of your code anyway, because it's confusing.

For memory leaks, I only want one warning. Something like:

A "may need cleanup" warning in Jou would either spam you with lots of false positive warnings, or it would be so complicated that it's basically impossible to implement.