LuaLS / LuaLS/lua-language-server

support nil checks on object fields

オープン
#1,361 コメント 3 件 リアクション 5 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず Lua のセットアップで問題を再現し、data.targetPosition に対する型の絞り込みと、ローカルのテスト変数に対する絞り込みを比較します。オブジェクトフィールドの nil チェックを処理する型解析の経路を追跡します。targetPos を demandMapPositionClass に渡したときに、オブジェクトフィールドの例で警告が出なくなれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
lua
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。