Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Enhancement] Infer @operator from implementations of metamethods #2941

Open
balt-dev opened this issue Nov 7, 2024 · 1 comment
Open

[Enhancement] Infer @operator from implementations of metamethods #2941

balt-dev opened this issue Nov 7, 2024 · 1 comment

Comments

@balt-dev
Copy link

balt-dev commented Nov 7, 2024

If an object's metatable implements the proper metamethods, LuaLS should be able to infer the @operator implementation.

Note that I may just be doing it wrong, as I'm using a class with a metatable of itself:

---@class Rule
---@field def fun(source: string, index: number): number, ...
T.Rule = {__metatable = false}
-- Prevent infinite recursion by not taking the shortcut of __index: table 
setmetatable(T.Rule, {
    __call = function(t, source, index) return t:parse(source, index) end,
    __index = function(t, k) if t ~= T.Rule then return T.Rule[k] end end,
    __newindex = function() error("cannot create fields on a value of type Rule") end,
    __metatable = false
})

---@param def fun(source: string, index: number): number, ...
---@return Rule
---@nodiscard
function T.Rule.new(def)
    local o = {def = def}
    setmetatable(o, T.Rule)
    return o
end

---@param other Rule
---@return Rule
---@nodiscard
function T.Rule:__add(other)
    return T.Rule.new(function(source, index)
        local succ, i = pcall(self.def, source, index)
        if not succ then error(i, 2) end

        return other.def(source, i)
    end)
end
@tomlau10
Copy link
Contributor

tomlau10 commented Nov 8, 2024

This has been feature requested before, but seems rejected by maintainer due to performance consideration: #599 (comment)

However maintainer is doing a v4.0.0 rewrite, maybe it can be supported in future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants