lua-language-server icon indicating copy to clipboard operation
lua-language-server copied to clipboard

Proposal: Add @constructor Tag for Class Constructors in Lua LSP

Open ErickProgramer opened this issue 11 months ago • 1 comments

This Lua LSP could benefit from a new @constructor tag, which would be used when defining classes, especially with libraries. Currently, we have to do something like this:

---@class myCls
---@overload fun(a: integer, b: integer): myCls
local myCls = class "myCls"

---@param a integer
---@param b integer
function myCls:__init(a, b)
     self.a = a
     self.b = b
end
local instance = myCls(10, 20)
print(instance)

As you can see, we need to create an overload for the variable, which makes the typing process quite repetitive. To address this, we could introduce a new @constructor tag that would automatically handle this:

---@class myCls
local myCls = class "myCls" -- No need for an overload anymore.

-- Defining this method as the constructor:
---@constructor
---@param a integer
---@param b integer
function myCls:__init(a, b)
     self.a = a
     self.b = b
end
local instance = myCls(10, 20) -- Type checking would work correctly and show the constructor parameters.
print(instance)

This approach would make the code cleaner and more intuitive, reducing the need for repetitive annotations and improving the overall developer experience.

ErickProgramer avatar Feb 07 '25 16:02 ErickProgramer

There has been feature requested before: https://github.com/LuaLS/lua-language-server/issues/449 And the @overload is the compromised result: https://github.com/LuaLS/lua-language-server/issues/449#issuecomment-1171213817


I am not maintainer, but I think there are some difficulties to implement the @constructor 😕 :

  • the function signature of the constructor function is different from the call function
    • myCls(10, 20) is fun(a, b): myCls
    • while myCls:__init(a, b) is fun(self, a, b): nil, there is an extra self as the 1st param
    • => they are different
  • this difficulty was discussed in another similar feature request: https://github.com/LuaLS/lua-language-server/issues/2920#issuecomment-2445939024

tomlau10 avatar Feb 10 '25 03:02 tomlau10