summaryrefslogtreecommitdiff
path: root/script/core/find-source.lua
blob: 26a411e5489113f4dbc5f47689cd30a7391568f4 (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
local guide     = require 'parser.guide'

local function isValidFunctionPos(source, offset)
    for i = 1, #source.keyword // 2 do
        local start  = source.keyword[i * 2 - 1]
        local finish = source.keyword[i * 2]
        if offset >= start and offset <= finish then
            return true
        end
    end
    return false
end

return function (ast, position, accept)
    local len = math.huge
    local result
    guide.eachSourceContain(ast.ast, position, function (source)
        if source.type == 'function' then
            if not isValidFunctionPos(source, position) then
                return
            end
        end
        local start, finish = guide.getStartFinish(source)
        if finish - start < len and accept[source.type] then
            result = source
            len = finish - start
        end
    end)
    return result
end