LuaLS / LuaLS/lua-language-server

Widening cast has no effect

未关闭
#2,215 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug
主要语言
Lua
星标
4.4k
派生
442
PR 合并指标
30 天内没有已合并 PR

描述

### How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

### Which OS are you using?

Linux

### What is the issue affecting?

Annotations, Type Checking, Hover

### Expected Behaviour

Cast unconditionally overwrites the variable's type with the new type.

### Actual Behaviour

Cast is ignored and in some cases causes additional type check errors.

### Reproduction steps

```lua
---@param str string
local function foo(str)
---@cast str +?
if str == '' then str = nil end
end
```
Note how it produces an error on assignment:
```
This variable is defined as type `string`. Cannot convert its type to `nil`.
- `nil` cannot match `string`
- Type `nil` cannot match `string` Lua Diagnostics.(cast-local-type)
```
Note also that the tooltip for `str` in the comparison says correctly that it is a `string?`. But this has no observable effect on the actual type.

Example two (attempted workaround):
```lua
---@param str string
local function foo(str)
---@cast str string?
if str == '' then str = nil end
end
```
Note how the cast causes a type check error now, which makes no sense.

Example three (from the wiki on cast, modified to actually verify that the cast worked):
```lua
---@type integer
local x

---@cast x +boolean
x = false
```
Note how it produces an error, similarly to the first example. You would expect at least the example from the official documentation itself to work, but it doesn't. This leads me to conclude this is a bug.

### Additional Notes

_No response_

### Log File

_No response_

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先运行 issue 中的三个 Lua 复现,并将悬停信息与赋值诊断进行比较。跟踪局部变量的 cast 处理以及后续的类型检查路径,然后添加或更新覆盖范围,使 widening cast 影响赋值检查,同时不引入相互矛盾的错误。

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

评估

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

把新 issue 发到你的邮箱

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