summaryrefslogtreecommitdiff
path: root/script-beta/vm/getGlobals.lua
blob: 69e6dbb7591cb7afe2a2bfe62e9f73dd68772e9b (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
local guide   = require 'parser.guide'
local vm      = require 'vm.vm'
local files   = require 'files'
local library = require 'library'

local function getGlobalsOfFile(uri)
    local globals = {}
    local ast = files.getAst(uri)
    if not ast then
        return globals
    end
    local env = guide.getENV(ast.ast)
    local results = guide.requestFields(env)
    for _, res in ipairs(results) do
        local name = guide.getSimpleName(res)
        if name then
            if not globals[name] then
                globals[name] = {}
            end
            globals[name][#globals[name]+1] = res
        end
    end
    return globals
end

local function insertLibrary(results, name)
    if name:sub(1, 2) == 's|' then
        results[#results+1] = library.global[name:sub(3)]
    end
end

local function getGlobals(name)
    local results = {}
    for uri in files:eachFile() do
        local cache = files.getCache(uri)
        cache.globals = cache.globals or getGlobalsOfFile(uri)
        if cache.globals[name] then
            for _, source in ipairs(cache.globals[name]) do
                results[#results+1] = source
            end
        end
    end
    insertLibrary(results, name)
    return results
end

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