summaryrefslogtreecommitdiff
path: root/server-beta/src/core/definition.lua
blob: 91d8f49964912546cb818d14342f49ce641163e2 (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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
local guide     = require 'parser.guide'
local workspace = require 'workspace'
local files     = require 'files'

local function findDef(searcher, source, callback)
    searcher:eachDef(source, function (info)
        local src = info.source
        local uri = info.uri
        if     src.type == 'setfield'
        or     src.type == 'getfield'
        or     src.type == 'tablefield' then
            callback(src.field, uri)
        elseif src.type == 'setindex'
        or     src.type == 'getindex'
        or     src.type == 'tableindex' then
            callback(src.index, uri)
        elseif src.type == 'getmethod'
        or     src.type == 'setmethod' then
            callback(src.method, uri)
        else
            callback(src, uri)
        end
    end)
end

---@param searcher engineer
local function checkRequire(searcher, source, offset, callback)
    if source.type ~= 'call' then
        return
    end
    local func = source.node
    local pathSource = source.args and source.args[1]
    if not pathSource then
        return
    end
    if not guide.isContain(pathSource, offset) then
        return
    end
    local literal = guide.getLiteral(pathSource)
    if type(literal) ~= 'string' then
        return
    end
    local name = searcher:getSpecialName(func)
    if     name == 'require' then
        local result = workspace.findUrisByRequirePath(literal, true)
        for _, uri in ipairs(result) do
            callback(uri)
        end
    elseif name == 'dofile'
    or     name == 'loadfile' then
        local result = workspace.findUrisByFilePath(literal, true)
        for _, uri in ipairs(result) do
            callback(uri)
        end
    end
end

return function (uri, offset)
    local results = {}
    local searcher = files.getSearcher(uri)
    if not searcher then
        return nil
    end
    guide.eachSourceContain(searcher.ast, offset, function (source)
        checkRequire(searcher, source, offset, function (uri)
            results[#results+1] = {
                uri    = uri,
                source = source,
                target = {
                    start  = 0,
                    finish = 0,
                }
            }
        end)
        findDef(searcher, source, function (target, uri)
            results[#results+1] = {
                target = target,
                uri    = uri,
                source = source,
            }
        end)
    end)
    if #results == 0 then
        return nil
    end
    return results
end