summaryrefslogtreecommitdiff
path: root/script/vm/node/compiler.lua
blob: 3c7466b5d1e4b58cf6f6e727ad0702c4d0341d18 (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
local guide  = require 'parser.guide'
local util   = require 'utility'
local state  = require 'vm.state'

---@class parser.guide.object
---@field _compiledGlobals      boolean
---@field _initedNodes          boolean
---@field _compiled             any

---@class vm.node.compiler
local m = {}

---@class vm.node.unknown
m.UNKNOWN = { type = 'unknown' }

---@alias vm.node vm.node.unknown | vm.node.global | vm.node.class

local compilerMap = util.switch()
    : case 'setglobal'
    : call(function (uri, source)
        local name = guide.getKeyName(source)
        source._compiled = state.declareGlobal(name, uri, source)
    end)
    : case 'getglobal'
    : call(function (uri, source)
        local name   = guide.getKeyName(source)
        local global = state.getGlobal(name)
        global:addGet(uri, source)
        source._compiled = global
    end)
    : getMap()

---@param uri    uri
---@param source parser.guide.object
---@return vm.node
function m.compileNode(uri, source)
    if source._compiled then
        return source._compiled
    end
    source._compiled = m.UNKNOWN
    local compiler = compilerMap[source.type]
    if compiler then
        compiler(uri, source)
    end
    return source._compiled
end

---编译全局变量的node
---@param  root parser.guide.object
function m.compileGlobals(root)
    if root._initedNodes then
        return
    end
    if root._compiledGlobals then
        return
    end
    root._compiledGlobals = true
    local uri = guide.getUri(root)
    local env = guide.getENV(root)
    if env.ref then
        for _, ref in ipairs(env.ref) do
            m.compileNode(uri, ref)
        end
    end
end

return m