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

Missing diagnostic when passing nil-able fields to pairs/ipairs

Open firas-assaad opened this issue 1 year ago • 1 comments

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, Diagnostics/Syntax Checking

Expected Behaviour

In the following code, I expect to get param-type mismatch for each of the for loops (with pairs and ipairs) because the variable being iterated can be nil:

---@type string[]?
local x1 = {}

for _ in ipairs(x1) do  -- param-type-mismatch: Cannot assign `string[]?` to parameter `<T:table>
    break
end

---@type table<string, boolean>?
local y1 = {}

for _ in ipairs(y1) do -- param-type-mismatch: Cannot assign `table<string, boolean>?` to parameter `<T:table>
    break
end

---@class Class
---@field x string[]?
---@field y table<string, boolean>?

---@type Class
local x2 = {}

for _ in ipairs(x2.x) do -- Should warn, but it doesn't
    break
end

for _ in pairs(x2.y) do -- Should warn, but it doesn't
    break
end

Actual Behaviour

The param-type-mismatch diagnostic is only shown for the first two loops (direct variables without nesting/fields), but not when using fields (the third and fourth for loops).

Reproduction steps

Copy the code into a Lua file and observe the diagnostics

Additional Notes

No response

Log File

No response

firas-assaad avatar Nov 25 '23 10:11 firas-assaad

Potentially related issue I frequently experience with pairs/ipairs is an incorrect diagnostic and syntax check thrown when used in a one-liner expression:

image Adding a new line after the if expression resolves this:

if (true) then
    for i, value in ipairs(example) do print(i, value) end
end

Or any other lexical token that is syntactically valid in this context, such as a tab ( ) character:

--             v Tab is here
if (true) then	for i, value in ipairs(example) do print(i, value) end end

ImSkully avatar Nov 26 '23 00:11 ImSkully