teal-language / tl

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

Generic arguments that map to function return values sometimes require that matching functions explicitly declare return type as nil #516

Open svermeulen opened 2 years ago

svermeulen commented 2 years ago
function decorate<TReturn>(action:(function():TReturn)):(function():TReturn)
   return function():TReturn
      print("before")
      local result = action()
      print("after")
      return result
   end
end

-- This fails to compile
-- local runner = decorate(function() print("test1") end)

-- This works
local runner = decorate(function():nil print("test1") end)

runner()

I'm not sure if this is a bug necessarily, but it seems to me that it would be nice if Teal considered nil as the default return type when unspecified.

hishamhm commented 2 years ago

There are observable behavior differences (e.g, select("#", f() )) between a Lua function that returns explicit nil with return nil (return arity 1) versus with return (return arity 0). In most situations, Lua adjusts the arity defaulting to nil. I haven't thought through if there are consequences to doing this here in the resolution of the generic's type variable, but my first thought is that this might lead to footguns when people forget to annotate types that are needed and then they silently resolve to nil. Again, I haven't fully analyzed this, but just wanted to share my first impression.