LuaLS / LuaLS/lua-language-server

Feature Request: Assertion Functions

オープン
#2,032 コメント 5 件 リアクション 5 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

enhancement
主要言語
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!

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず TypeScript 3.7 の assertion-functions リファレンスと、リンクされている type-predicate の issue 704 を読み、次に既存の @cast アノテーションがどのように narrowing を行うかを調べます。アサーション呼び出しが成功した後に Lua のアサーションアノテーションで引数を絞り込めるようになり、その結果 yell の例で別個の cast なしに str:upper() を受け入れられれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
lua, typescript
領域
tooling
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
30/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。