Skip to content

Commit cad34b7

Browse files
committed
perf: Optimize undefined-field check early break logic
The current early break only wants to check if there are any definition. There is no need to fetch the full definitions list. We can early break as soon as we found the 1st one.
1 parent fea3b6d commit cad34b7

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

script/core/diagnostics/undefined-field.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ return function (uri, callback)
2121
local function checkUndefinedField(src)
2222
await.delay()
2323

24-
if #vm.getDefs(src) > 0 then
24+
if vm.hasDef(src) then
2525
return
2626
end
2727
local node = src.node

script/vm/def.lua

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,42 @@ function vm.getDefs(source)
9292

9393
return results
9494
end
95+
96+
local HAS_DEF_ERR = {} -- the error object for comparing
97+
local function checkHasDef(checkFunc, source, pushResult)
98+
local _, err = pcall(checkFunc, source, pushResult)
99+
return err == HAS_DEF_ERR
100+
end
101+
102+
---@param source parser.object
103+
function vm.hasDef(source)
104+
local mark = {}
105+
local hasLocal
106+
local function pushResult(src)
107+
if src.type == 'local' then
108+
if hasLocal then
109+
return
110+
end
111+
hasLocal = true
112+
if source.type ~= 'local'
113+
and source.type ~= 'getlocal'
114+
and source.type ~= 'setlocal'
115+
and source.type ~= 'doc.cast.name' then
116+
return
117+
end
118+
end
119+
if not mark[src] then
120+
mark[src] = true
121+
if guide.isAssign(src)
122+
or guide.isLiteral(src) then
123+
-- break out on 1st result using error() with a unique error object
124+
error(HAS_DEF_ERR)
125+
end
126+
end
127+
end
128+
129+
return checkHasDef(searchBySimple, source, pushResult)
130+
or checkHasDef(searchByLocalID, source, pushResult)
131+
or checkHasDef(vm.compileByNodeChain, source, pushResult)
132+
or checkHasDef(searchByNode, source, pushResult)
133+
end

0 commit comments

Comments
 (0)