LuaLS / LuaLS/lua-language-server

support nil checks on object fields

未關閉
#1,361 3 則留言 5 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

enhancement
主要語言
Lua
星號
4.4k
分支
442
PR 合併指標
30 天內沒有已合併 PR

描述

At present a variable's nil check is recognised as meaning the variable can't have a type of nil within the code block, but this doesn't work for object fields.

Setup code:

---@class MapPosition
---@field x integer
---@field y integer

---@class Data
---@field targetPosition MapPosition|nil

---@type Data
local data = {
    targetPosition = nil
}

---@param x MapPosition
local function demandMapPositionClass(x)
end

Object field code that doesn't work as it misses the nil check.

--- Object field nil check
local targetPos  ---@type MapPosition
if data.targetPosition ~= nil then
    targetPos = data.targetPosition -- This has set targetPos to a type of nil or MapPosition. But a nil value can't enter this block.
else
    targetPos = {x = 1, y = 1}
end
demandMapPositionClass(targetPos) -- This warns as targetPos can now contain nil.

Variable code that works correctly with it auto detecting the nil check.

--- Variable nil check
local targetPos2  ---@type MapPosition
local test = data.targetPosition
if test ~= nil then
    targetPos2 = test -- This correctly knows that test can only be of type MapPosition.
else
    targetPos2 = {x = 1, y = 1}
end
demandMapPositionClass(targetPos2)

I can fix the object field check with an @as on the offending line to force it to the right data type, but this isn't as futureproofed for later code changes. Also making a new variable just for this to magically works seems a waste and misleading when reading the code as you'd assume a variable is used later on for a specific purpose and not just to help Sumneko intellisense,

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先使用 Lua 設定重現問題,並比較 data.targetPosition 的型別縮窄與區域測試變數的型別縮窄。追蹤處理物件欄位 nil 檢查的型別分析路徑;當將 targetPos 傳入 demandMapPositionClass 時,物件欄位範例不再發出警告,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
lua
領域
devtools
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。