summaryrefslogtreecommitdiff
path: root/server/src/core/find_source.lua
blob: 65df6b950b66dfcc864f9dd1d90b9943e6830db3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
local function isContainPos(obj, pos)
    if obj.start <= pos and obj.finish + 1 >= pos then
        return true
    end
    return false
end

local function isValidSource(source)
    return source.start ~= nil and source.start ~= 0
end

local function findAtPos(sources, pos, level)
    local res = {}
    for _, source in ipairs(sources) do
        if isValidSource(source) and isContainPos(source, pos) then
            res[#res+1] = source
        end
    end
    if #res == 0 then
        return nil
    end
    table.sort(res, function (a, b)
        local rangeA = a.finish - a.start
        local rangeB = b.finish - b.start
        return rangeA < rangeB
    end)
    local source = res[level or 1]
    if not source then
        return nil
    end
    return source
end

return function (vm, pos, level)
    return findAtPos(vm.sources, pos, level)
end