Skip to content

feat: infer function param when the function is passed as call arg #2946

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 3 commits into from
Nov 11, 2024

Conversation

tomlau10
Copy link
Contributor

@tomlau10 tomlau10 commented Nov 9, 2024

closes #2695 (the feature request by me, finally I have the knowledge to implement myself 🙂 )

  • This supports inferring function param type when the local function is used as call argument, and that the argument has a fun() annotation.
  • This is actually an improvement to the existing Lua.type.inferParamType logic, so this feature is only enabled when this config is set to true.

Example Use Case

---@param callback fun(a: integer)
function register(callback) end

local function callback(a) end  --> a: integer
register(callback)

which is similar to existing infer behavior with function literal:

register(function (a)  --> a: integer
end)

中文版

  • 具體應用例子見上邊
  • 在效果上來說跟現有的 function literal infer param type 基本相同,只不過是應用到 local function 的 param 上
  • 這個算是對現有 Lua.type.inferParamType 功能的延伸,所以要開啟這個 config 才會生效

實現思路

  • 在 infer 1個未被 annotate 的 local function param type 時
    如果這個 function variable 是在某次 call 中作為 arg
    應該是可以嘗試用該 arg 位置的 doc.type.function (如有) 來進一步 infer
  • 而在早些時間我研究這裡的 completion 問題時: Function Overloading Overhaul (@function annotation) #1456 (comment)
    我找到原來有1個 vm.compileCallArg() 可以 compile 某個 call 行為的指定 index argument type
  • 那麼對於有使用在 call arg 的 function variable 來說
    • 首先我利用上述 function 來模擬觸發1次 completion => 獲取在 cbIndex 的 arg infer type
    • 如果這裡的 infer type 帶有 doc.type.function,則再利用這 function 的 args[aindex] (當前 local function param index) 的 type 來做 infer
    • 如果找到 infer type 的話就 merge 入當前 param type

@sumneko sumneko merged commit af662de into LuaLS:master Nov 11, 2024
11 checks passed
@tomlau10 tomlau10 deleted the feat/infer_callback_param branch November 11, 2024 12:00
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support auto complete of callback arguments where callback is defined via a local variable
2 participants