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