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:
```lua
---@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.
```lua
--- 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.
```lua
--- 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 检查的类型分析路径;当向 demandMapPositionClass 传入 targetPos 时,对象字段示例不再发出警告,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
lua
领域
devtools
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。