LuaLS / LuaLS/lua-language-server

support nil checks on object fields

Offen
#1,361 3 Kommentare 5 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

enhancement
Vorherrschende Sprache
Lua
Sterne
4.4k
Forks
442
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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,

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, das Problem mit dem Lua-Setup zu reproduzieren, und vergleiche die Typverengung für data.targetPosition mit der Verengung für die lokale Testvariable. Verfolge den Pfad der Typanalyse, der nil-Prüfungen an Objektfeldern verarbeitet; fertig ist die Aufgabe, wenn das Beispiel mit dem Objektfeld keine Warnung mehr ausgibt, wenn targetPos an demandMapPositionClass übergeben wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
lua
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.