summaryrefslogtreecommitdiff
path: root/script/vm/state.lua
blob: 83ce6084430b71580c25d3cdfa6d13b508111776 (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
local util       = require 'utility'
local files      = require 'files'
local globalNode = require 'vm.global-node'

---@class vm.state
local m = {}
---@type table<uri, parser.object[]>
m.literals = util.multiTable(2)
---@type table<parser.object, table<parser.object, boolean>>
m.literalSubs = util.multiTable(2, function ()
    return setmetatable({}, util.MODE_K)
end)
---@type table<parser.object, boolean>
m.allLiterals = {}

---@param uri    uri
---@param source parser.object
function m.declareLiteral(uri, source)
    if m.allLiterals[source] then
        return
    end
    m.allLiterals[source] = true
    local literals = m.literals[uri]
    literals[#literals+1] = source
end

---@param source parser.object
---@param node   vm.node
function m.subscribeLiteral(source, node)
    if not node then
        return
    end
    if node.type == 'union'
    or node.type == 'cross' then
        node:subscribeLiteral(source)
        return
    end
    if not m.allLiterals[source] then
        return
    end
    m.literalSubs[node][source] = true
end

---@param uri uri
function m.dropUri(uri)
    local literals = m.literals[uri]
    m.literals[uri] = nil
    for _, literal in ipairs(literals) do
        m.allLiterals[literal] = nil
        local literalSubs = m.literalSubs[literal]
        m.literalSubs[literal] = nil
        for source in pairs(literalSubs) do
            source._node = nil
        end
    end
end

for uri in files.eachFile() do
    local state = files.getState(uri)
    if state then
        globalNode.compileAst(state.ast)
    end
end

files.watch(function (ev, uri)
    if ev == 'update' then
        local state = files.getState(uri)
        if state then
            globalNode.compileAst(state.ast)
        end
    end
    if ev == 'remove' then
        m.dropUri(uri)
        globalNode.dropUri(uri)
    end
end)


return m