LuaLS / LuaLS/lua-language-server

Ability to mark default constructor names for resolving return type

未关闭
#2,331 0 条评论 2 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 issue 中的 class.lua 和 example.lua 场景开始,重点关注 ---@class 注解和 new() 调用是如何解析的。在选择方案之前,查看 issue #449 中的相关讨论以及所描述的 @field 替代方案。完成的实现应包括推断出的构造函数可用性,以及示例中正确的实例返回类型。

由索引模型根据 Issue 内容生成。

评估

技术栈
lua
领域
devtools
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。