LuaLS / LuaLS/lua-language-server
support nil checks on object fields
Nessuno ha ancora preso questa issue.
- Lingua principale
- Lua
- Stelle
- 4.4k
- Fork
- 442
- Metriche di merge delle PR
- Nessuna PR unita negli ultimi 30g
Descrizione
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,
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia riproducendo il problema con la configurazione Lua e confronta il restringimento dei tipi per data.targetPosition con quello per la variabile di test locale. Traccia il percorso di analisi dei tipi che gestisce i controlli nil sui campi degli oggetti; il lavoro è completo quando l’esempio con il campo dell’oggetto non genera più un avviso quando targetPos viene passato a demandMapPositionClass.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- lua
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 45/100