summaryrefslogtreecommitdiff
path: root/script-beta/vm/getLinks.lua
blob: 41318e1c7cb7dfe0be193df61e84723d2e639844 (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
local guide = require 'parser.guide'
local vm    = require 'vm.vm'
local files = require 'files'

local function getFileLinks(uri)
    local links = {}
    local ast = files.getAst(uri)
    if not ast then
        return links
    end
    guide.eachSpecialOf(ast.ast, 'require', function (source)
        local call = source.parent
        if not call or call.type ~= 'call' then
            return
        end
    end)
    return links
end

local function getLinksTo(uri)
    local links = {}
    local mark = {}
    for u in files.eachFile() do
        local l = vm.getFileLinks(u)
        for _, lu in ipairs(l) do
            if files.eq(uri, lu) then
                local ku = files.asKey(u)
                if not mark[ku] then
                    mark[ku] = true
                    links[#links+1] = u
                end
            end
        end
    end
    return links
end

function vm.getLinksTo(uri)
    local cache = vm.getCache('getLinksTo')[uri]
    if cache ~= nil then
        return cache
    end
    cache = getLinksTo(uri)
    vm.getCache('getLinksTo')[uri] = cache
    return cache
end

function vm.getFileLinks(uri)
    local cache = files.getCache(uri)
    cache.links = cache.links or getFileLinks(uri)
    return cache.links
end