LuaLS / LuaLS/lua-language-server

`need-check-nil` doesn't recognize nil check propagation

Open
#1,997 3 comments 4 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
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?

MacOS

What is the issue affecting?

Diagnostics/Syntax Checking

Expected Behaviour

Ideally, need-check-nil would infer a nil check has been completed if I've already done that nil check earlier as part of a larger check. Specifically, the statement if not (a and a.b) then will properly register as a nil check on a, but assigning the inner expression to a local var prevents LLS from detecting it as a nil check.

Actual Behaviour

LLS warns need-check-nil when a variable cannot possibly be nil, if the check was masked via another variable.

Reproduction steps
---@return table?
local function stuff()
    return nil
end

local item = stuff()
local x = item and item.x
if not x then -- Works: `if not (item and item.x) then`
   -- This includes case where `item` is `nil` 
else
    local subitem = item.key -- Error on `item` (need-check-nil)
end
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 need-check-nil diagnostic in the Visual Studio Code extension with the Lua example in the issue, then trace the diagnostic's nil-check propagation logic. Done means the example no longer warns on item.key when the earlier check through x already excludes item from being nil.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.