Skip to content

Commit e64e422

Browse files
committed
feat: infer function param when the function is passed as call arg
1 parent e890588 commit e64e422

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

script/vm/compiler.lua

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,56 @@ local function compileFunctionParam(func, source)
12091209
end
12101210
::continue::
12111211
end
1212-
return found
1212+
if found then
1213+
return true
1214+
end
1215+
-- infer local callback function param type
1216+
--[[
1217+
---@param callback fun(a: integer)
1218+
function register(callback) end
1219+
1220+
local function callback(a) end --> a: integer
1221+
register(callback)
1222+
]]
1223+
for _, ref in ipairs(refs) do
1224+
if ref.parent.type ~= 'callargs' then
1225+
goto continue
1226+
end
1227+
-- the parent function is a variable used as callback param, find the callback arg index first
1228+
local call = ref.parent.parent
1229+
local cbIndex
1230+
for i, arg in ipairs(call.args) do
1231+
if arg == ref then
1232+
cbIndex = i
1233+
break
1234+
end
1235+
end
1236+
---@cast cbIndex integer
1237+
1238+
-- simulate a completion at `cbIndex` to infer this callback function type
1239+
---@diagnostic disable-next-line: missing-fields
1240+
local node = vm.compileCallArg({ type = 'dummyarg', uri = guide.getUri(call) }, call, cbIndex)
1241+
if not node then
1242+
goto continue
1243+
end
1244+
for n in node:eachObject() do
1245+
-- check if the inferred function has arg at `aindex`
1246+
if n.type == 'doc.type.function' and n.args and n.args[aindex] then
1247+
-- use type info on this `aindex` arg
1248+
local argNode = vm.compileNode(n.args[aindex])
1249+
for an in argNode:eachObject() do
1250+
if an.type ~= 'doc.generic.name' then
1251+
vm.setNode(source, an)
1252+
found = true
1253+
end
1254+
end
1255+
end
1256+
end
1257+
::continue::
1258+
end
1259+
if found then
1260+
return true
1261+
end
12131262
end
12141263

12151264
do

0 commit comments

Comments
 (0)