LuaLS / LuaLS/lua-language-server

Ipairs with generic

Open
#2,969 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Lua
Stars
4.4k
Forks
442
PR merge metrics
No merged PRs in 30d

Description

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Windows

What is the issue affecting?

Annotations

Expected Behaviour

Should have got a correct type inference in a generic function.

Actual Behaviour
  1. could not specify a V-related type for result in the generic function
  2. ipairs will be inferred as unknown
  3. returns of the generic function will be inferred as a strange type
Reproduction steps
---@class Test
---@field name string

---@type Test[]
local tests = {
    { name = "test1" },
    { name = "test2" },
    { name = "test3" },
}

--[[
CORRECT:
    function group_by(rows: <V>[], key: string)
    -> table<string, <V>[]>
]]
---@generic V
---@param rows V[]
---@param key string
---@return table<string, V[]>
local function group_by(rows, key)
    --[[
        ---@type table<string, V[]>
        GOT: Undefined type or alias `V`.
    ]]
    local result = {}
    -- WRONG: local v: unknown
    for i, v in ipairs(rows) do
        local k = v[key]
        if not result[k] then
            result[k] = {}
        end
        table.insert(result[k], v)
    end
    return result
end

--[[
WRONG:
    local groups: table<string, <V>[]> | { [<K>]: Test }
EXPECTED:
    local groups: table<string, Test[]>
]]
local groups = group_by(tests, "name")

Additional Notes

No response

Log File

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the Lua snippet from the issue and inspect the language server's generic annotation, indexed-access, and ipairs type-inference paths. Done means V is accepted in the local result annotation, ipairs yields the generic element type, and group_by(tests, "name") is inferred as table<string, Test[]>.

Written by the indexing model from the issue text.

Assessment

Tech stack
lua
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.