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

Break in loop makes variable go out of scope early? #2912

Open PennyJim opened 1 month ago

PennyJim commented 1 month ago

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Linux

What is the issue affecting?

Type Checking

Expected Behaviour

I was trying to fetch a table that could be within a number of tables. Leaving early if it was found

I wanted that locally scoped variable to be the same type after the loop as before it

Actual Behaviour

Only for my variable scoped outside the loop to be unknown after it. In an attempt to band-aid what I originally luals choking a little, I tried casting it. Only to find it was in fact unaware it even existed.

Reproduction steps

As minimal I can get the code to be and reproduce it:

---@type {[any]:A}
local T

function F()
    ---@class A
    local a

    for _, i in pairs{} do
        a = T[1]
        if a then break end
    end

    -- See it complain the `a` variable
    ---@cast a A
end

Additional Notes

No response

Log File

service.log

tomlau10 commented 1 month ago

In an attempt to band-aid what I originally luals choking a little, I tried casting it. Only to find it was in fact unaware it even existed.

There is another strange bug that existed for a while. When you use @cast on a variable which has no more access to it later, it will complain unless the file has a trailing newline (yeah~ strange 🙈 ) see: https://github.com/LuaLS/lua-language-server/issues/2326