summaryrefslogtreecommitdiff
path: root/script-beta/vm/eachDef.lua
blob: 89a67369138889fc564b929c7f031d56ed29970d (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
88
89
90
local vm    = require 'vm.vm'
local guide = require 'parser.guide'
local files = require 'files'

local function checkPath(source, info)
    if source.type == 'goto' then
        return true
    end
    local src = info.source
    local mode = guide.getPath(source, src)
    if not mode then
        return true
    end
    if mode == 'before' then
        return false
    end
    return true
end

function vm.eachDef(source, callback)
    local results = {}
    local returns = {}
    local infoMap = {}
    local sourceUri = guide.getRoot(source).uri
    vm.eachRef(source, function (info)
        if info.mode == 'declare'
        or info.mode == 'set' then
            results[#results+1] = info
        end
        if info.mode == 'return' then
            results[#results+1] = info
            local root = guide.getParentBlock(info.source)
            if root.type == 'main' then
                returns[root.uri] = info
            end
        end
        infoMap[info.source] = info
    end)

    local function pushDef(info)
        local res = callback(info)
        if res ~= nil then
            return res
        end
        local value = info.source.value
        local vinfo = infoMap[value]
        if vinfo then
            res = callback(vinfo)
        end
        return res
    end

    local res
    local used = {}
    for _, info in ipairs(results) do
        local src = info.source
        local destUri
        if used[src] then
            goto CONTINUE
        end
        used[src] = true
        destUri = guide.getRoot(src).uri
        -- 如果是global或field,则直接放行(因为无法确定顺序)
        if src.type == 'setindex'
        or src.type == 'setfield'
        or src.type == 'setmethod'
        or src.type == 'tablefield'
        or src.type == 'tableindex'
        or src.type == 'setglobal' then
            res = pushDef(info)
            goto CONTINUE
        end
        -- 如果是同一个文件,则检查位置关系后放行
        if sourceUri == destUri then
            if checkPath(source, info) then
                res = pushDef(info)
            end
            goto CONTINUE
        end
        -- 如果不是同一个文件,则必须在该文件 return 后才放行
        if returns[destUri] then
            res = pushDef(info)
            goto CONTINUE
        end
        ::CONTINUE::
        if res ~= nil then
            return res
        end
    end
end