LuaLS / LuaLS/lua-language-server
[Request] Improve support for custom number types
还没有人认领这个 Issue。
- 主要语言
- Lua
- 星标
- 4.4k
- 派生
- 442
- PR 合并指标
- 30 天内没有已合并 PR
描述
In the builtin definitions, the `integer` type is defined as a child class of the `number` type:
```Lua
---@class integer : number
```
Despite that, it is still possible to write such code without any type-checking errors:
```Lua
---@param lives integer
local function printLives(lives)
print(lives)
end
---@type number
local lives = 9.0
printLives(lives)
```
I think this is fine, it makes sense.
However, this behaviour seems to be hardcoded in the extension.
Many of the functions from the API I use expect fixed-point values as parameters; such arguments are indicated by the `fixed` type, which is an alternate number type defined in much the same way as `integer`:
```Lua
---@class fixed : number
```
To represent literal fixed-point values, the API provides a unit contant which is used something like this:
```Lua
move(4*UNIT, 10*UNIT, UNIT*3/2) -- 40.0, 100.0, 1.5
```
Technically, `fixed` is just a regular number, however it is extremely helpful to the user to see this:

rather than this:

In older versions of the extension, this works perfectly fine; however, recent versions perform type-checking, which is a very useful feature but does not work nicely with the `fixed` type:

It looks like the extension considers `number * fixed` to be a `number`, which is a reasonable guess, but causes the error shown in the image above.
To solve this, I have thought of the following solutions:
1. Completely disabling type-checking. It works, obviously, but it would be preferable to not have to give up on such a useful feature.
2. Manually casting every literal value. This works too, but is extremely unpractical and results in bloating code.
3. Somehow make it so that `number * fixed` resolves to `fixed` instead of `number`. But that sounds like a very arbitrary solution to me.
4. Defining `fixed` as an alias: `---@alias fixed number`. It prevents the error from occuring, and the code is readable, but the completion/hover hints show "number" instead of "fixed", like in the second image.
5. Forking the extension to add a special case in the type checker.
There may also be other solutions I am not aware of, but my first impression is that solution 4 suits my usecase best, and would probably be perfect if there was some way to make an alias that behaves like in the first image (much like `typedef` in C, for instance).
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 `integer` 和 `number` 的内置定义开始,然后追踪涉及 `fixed` 等自定义数字类型的算术运算的类型检查器行为。完成的标准是:自定义数字类型无需 casts 即可保留有用的类型检查以及补全或悬停信息,同时保留现有的 `integer` 行为。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- lua
- 领域
- devtools
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100