LuaLS / LuaLS/lua-language-server
Feature Request: Assertion Functions
还没有人认领这个 Issue。
- 主要语言
- Lua
- 星标
- 4.4k
- 派生
- 442
- PR 合并指标
- 30 天内没有已合并 PR
描述
I would like annotation and type checking that supports and implements TypeScript's "Assertion Functions":
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions
It's similar to other open feature requests for type predicates / narrowing except it avoids the need for if statements and to return a boolean from the function where true means a variable is of a given type and false if it's not that type.
I mentioned this briefly in another open issue but the original issue was for implementing narrowing/type predicates:
https://github.com/LuaLS/lua-language-server/issues/704#issuecomment-1484060572
This TypeScript code illustrates the feature:
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new AssertionError("Not a string!");
}
}
This tells the linter that the argument passed to the val parameter is a string if no assertion raised an error.
In Lua, this might look like the following:
---@param val any
---@asserts val is string
local function assertIsString(val)
assert(type(val) == "string", "Not a string!")
end
---@param str any
local function yell(str)
assertIsString(str)
-- No error was thrown! Therefore, the next line should not be marked as a warning and `str` must be a string.
return str:upper()
end
The problem at the moment is that I need to add ---@cast val string after every usage of assertIsString:
local function yell(str)
assertIsString(str)
---@cast str string
return str:upper() -- LuaLS complains that str might not be a string unless I cast it
end
There is no other way of telling LuaLS that the result has been confirmed to be a string unless the assert expression is directly in the same body of code.
I would suggest adding narrowing with type predicates first as this feature request seems like the next feature on top of that feature, but I'd like to see what people think :)
Thank you!
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先阅读 TypeScript 3.7 的 assertion-functions 参考以及链接的 type-predicate issue 704,然后检查现有的 @cast 注解如何执行 narrowing。完成的标准是:Lua assertion 注解能够在 assertion 调用成功后缩小参数的类型,从而使 yell 示例无需单独的 cast 即可接受 str:upper()。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- lua, typescript
- 领域
- tooling
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 30/100