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

local function eachFieldInLibrary(source, lib, results)
    if not lib or not lib.child then
        return
    end
    for _, value in pairs(lib.child) do
        results[#results+1] = value
    end
end

local function eachFieldOfLibrary(results)
    for _, lib in pairs(library.global) do
        results[#results+1] = lib
    end
end

local function eachField(source)
    while source.type == 'paren' do
        source = source.exp
    end
    local results = guide.requestFields(source)
    local lib = vm.getLibrary(source)
    if lib then
        eachFieldInLibrary(source, lib, results)
    end
    if source.special == '_G' then
        eachFieldOfLibrary(results)
    end
    if library.object[source.type] then
        eachFieldInLibrary(source, library.object[source.type], results)
    end
    return results
end

function vm.eachField(source, callback)
    local cache = vm.cache.eachField[source]
    if cache ~= nil then
        for i = 1, #cache do
            callback(cache[i])
        end
        return
    end
    local unlock = vm.lock('eachField', source)
    if not unlock then
        return
    end
    cache = eachField(source) or false
    vm.cache.eachField[source] = cache
    unlock()
    for i = 1, #cache do
        callback(cache[i])
    end
end