LuaLS / LuaLS/lua-language-server

Ability to mark default constructor names for resolving return type

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

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

主要言語
Lua
スター
4.4k
フォーク
442
PR マージ指標
30日以内にマージされた PR はありません

説明

Hi!

A request to infer return value for default returns when calling a defined constructor function. EmmyLua supports this using a setting:
image

Here it can infer that calling e.g. :new() on items marked with the ---@class annotation will be returning an instance of that class.

This is especially useful when constructing classes using metatables in a generic class system, adding interfaces or inheritance functionality but still be able to denote the return type of calling the constructor method.

Example:

#class.lua

local definitions = {}

local Class = {}
function Class.class(name)
    local definitions = {}

    local def = definitions[name]
    if not def then
		def = {}
		def.__class_name = class_name

		def.new = function(self, ...)
	    	local instance = {}

	    	if instance.construct then
                instance:construct(...)
            end

            return instance
    	end

    	setmetatable(instance, def)

    	def[class_name] = def
	end

	return class_definition
end

Example of using the class creation method

#my_class.lua

local Class = require "path/class"

local MyClass = Class("MyClass")
function MyClass:construct()
	self._member = 0
end

Example of instantiating an instance of the class and showing the issue:

#example.lua

local MyClass = require "path/my_class"
local instance = MyClass:new() -- this line cannot find the function new() or deduce the return/type of "instance"

Here the instance of class return value from the new() function cannot be inferred and I haven't found a way to annotate this using luadocs with generics, alias, overload or other methods. This issue is somewhat related to #449 but I feel this warrants a retake on the proposed solution unless I am missing something?

A different way could be to allow explicit descriptors of the @field annotation to specify return value types in class definitions e.g.

image

The return values of functions defined in fields from a set metatable cannot have it's return type defined however it seems.

image

image

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

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

はじめの一歩

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

調査の方向性

issue の class.lua と example.lua のシナリオから始め、---@class アノテーションと new() 呼び出しがどのように解決されるかに焦点を当ててください。アプローチを選択する前に、issue #449 の関連する議論と、説明されている @field の代替案を確認してください。完了時には、推論されたコンストラクターの利用可能性と、例における正しいインスタンスの戻り値型を含める必要があります。

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

評価

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

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

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