LuaLS / lua-language-server

A language server that offers Lua language support - programmed in Lua
https://luals.github.io
MIT License
3.38k stars 319 forks source link

Index an enum-value table bug #2921

Open ChouUn opened 3 weeks ago

ChouUn commented 3 weeks ago

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?

Type Checking

Expected Behaviour

expected the value type of mapping when index

Actual Behaviour

got an unknown

Reproduction steps

---@enum(key) AttrName
local o = {
    ['hp_max'] = true,
}
local map = {
    ['hp_max'] = 114514,
}
---@param t table<AttrName, number>
local function test(t)
    --[[
        Usage 1: correct
    ]]
    local a = 'hp_max'
    local b = t[a]  -- expected: number, got: number
    print(b)

    --[[
        Usage 2: incorrect
    ]]
    local c = t['hp_max'] -- expected: number, got: unknown
    print(c)

    --[[
        Usage 3: correct
    ]]
    local d = "hp_grow"
    local e = t[d] -- expected: unknown, got: unknown
    print(e)
end
test(map)

Additional Notes

No response

Log File

No response

tomlau10 commented 3 weeks ago

similar issue: https://github.com/LuaLS/lua-language-server/issues/2791


And as a bonus case for the code snippet above:

--[[
    Usage 4: incorrect
]]
local x
local y = t[x] -- expected: unknown, got: number

seems when using unknown key to index this table, it will incorrectly infer as number as well