teal-language / tl

The compiler for Teal, a typed dialect of Lua
MIT License
2.12k stars 107 forks source link

spurious warning when most of the stuff are in a final return #677

Closed fperrad closed 1 year ago

fperrad commented 1 year ago
$ cat say_bad.tl 
local print = print
local type = type
local _ENV = nil

return {
    say = function (msg: any)
        if msg is string then
            print(msg)
        end
    end,
}
$ tl gen --check say_bad.tl 
Wrote: say_bad.lua
========================================
1 warning:
say_bad.tl:2:7: unused function type: function(<any type>): string
$ cat say_bad.lua 
local print = print
local type = type
local _ENV = nil

return {
   say = function(msg)
      if type(msg) == "string" then
         print(msg)
      end
   end,
}

This rewrite (more or less equivalent) does not generate warning

$ cat say_good.tl 
local print = print
local type = type
local _ENV = nil

local function say(msg: any)
    if msg is string then
        print(msg)
    end
end

return {
    say = say
}
$ tl gen --check say_good.tl 
Wrote: say_good.lua

in both version, the use of function print is correctly detected. in first version, the use of function type (generated from is) is not detected.

note:

$ tl --version
0.15.2
$ lua -v
Lua 5.4.6  Copyright (C) 1994-2023 Lua.org, PUC-Rio
hishamhm commented 1 year ago

in first version, the use of function type (generated from is) is not detected.

I wouldn't expect generated code to be counted as a variable use. In that sense, I'd say that is the expected behavior, and that the second version is the weird one. If you were getting warnings in both, I would reply that this is the expected behavior and that the Teal code generator generally auto-inserts these local boilerplate entries at the beginning of a file (though it does for a bunch of standard library entries because of compat, but not all). But since we're getting different behavior on things that should be equivalent, something is amiss and this is worth investigating further.

hishamhm commented 1 year ago

@fperrad I've fixed the code so that both examples report that local type = type went unused.

fperrad commented 1 year ago

Make sense when a boilerplate is generated, and this is the default behavior of tl.

But with --gen-compat off, is it possible to have another behavior ?

hishamhm commented 1 year ago

The internals of code generation shouldn't leak to the high-level Teal code like that. It would be super puzzling to have a unused-variable warning appear or not depending on invisible code.

If the reason why you want to have local type = type in your code is as a micro-optimization due to Teal's use of type() when generating of is, then what would be best would be to have Teal generate that local type = type on its own, instead of having the programmer add it.