summaryrefslogtreecommitdiff
path: root/script/lazytable.lua
blob: f964f236c664fff753470fe2de78c1666db5104f (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
local type    = type
local pairs   = pairs
local error   = error
local next    = next
local load    = load
local setmt   = setmetatable
local rawset  = rawset
local sdump   = string.dump
local sbyte   = string.byte
local smatch  = string.match
local sformat = string.format
local tconcat = table.concat

_ENV = nil

---@class lazytable.builder
---@field source     table
---@field codeMap    table<integer, string>
---@field dumpMark   table<table, integer>
---@field excludes   table<table, true>
---@field refMap     table<any, integer>
---@field instMap    table<integer, table|function|thread|userdata>
local mt = {}
mt.__index = mt
mt.tableID = 1
mt.keyID   = 1

local DUMMY = function() end

local RESERVED = {
    ['and']      = true,
    ['break']    = true,
    ['do']       = true,
    ['else']     = true,
    ['elseif']   = true,
    ['end']      = true,
    ['false']    = true,
    ['for']      = true,
    ['function'] = true,
    ['if']       = true,
    ['in']       = true,
    ['local']    = true,
    ['nil']      = true,
    ['not']      = true,
    ['or']       = true,
    ['repeat']   = true,
    ['return']   = true,
    ['then']     = true,
    ['true']     = true,
    ['until']    = true,
    ['while']    = true,
    ['goto']     = true
}

---@param k string|integer
---@return string
local function formatKey(k)
    if type(k) == 'string' then
        if not RESERVED[k] and smatch(k, '^[%a_][%w_]*$') then
            return k
        else
            return sformat('[%q]', k)
        end
    end
    if type(k) == 'number' then
        return sformat('[%q]', k)
    end
    error('invalid key type: ' .. type(k))
end

---@param v string|number|boolean
local function formatValue(v)
    return sformat('%q', v)
end

---@param info {[1]: table, [2]: integer, [3]: table?}
---@return string
local function dump(info)
    local codeBuf = {}

    codeBuf[#codeBuf + 1] = 'return{{'
    local hasFields
    for k, v in pairs(info[1]) do
        if hasFields then
            codeBuf[#codeBuf + 1] = ','
        else
            hasFields = true
        end
        codeBuf[#codeBuf+1] = sformat('%s=%s'
            , formatKey(k)
            , formatValue(v)
        )
    end
    codeBuf[#codeBuf+1] = '}'

    codeBuf[#codeBuf+1] = sformat(',%d', formatValue(info[2]))

    if info[3] then
        codeBuf[#codeBuf+1] = ',{'
        hasFields = false
        for k, v in pairs(info[3]) do
            if hasFields then
                codeBuf[#codeBuf+1] = ','
            else
                hasFields = true
            end
            codeBuf[#codeBuf+1] = sformat('%s=%s'
                , formatKey(k)
                , formatValue(v)
            )
        end
        codeBuf[#codeBuf+1] = '}'
    end

    codeBuf[#codeBuf + 1] = '}'

    return tconcat(codeBuf)
end

---@param obj table|function|userdata|thread
---@return integer
function mt:getObjectID(obj)
    if self.dumpMark[obj] then
        return self.dumpMark[obj]
    end
    local id = self.tableID
    self.tableID = self.tableID + 1
    self.dumpMark[obj] = id
    if self.excludes[obj] or type(obj) ~= 'table' then
        self.refMap[obj] = id
        self.instMap[id] = obj
        return id
    end

    if not next(obj) then
        self.codeMap[id] = nil
        return id
    end

    local fields = {}
    local objs
    for k, v in pairs(obj) do
        local tp = type(v)
        if tp == 'string' or tp == 'number' or tp == 'boolean' then
            fields[k] = v
        else
            if not objs then
                objs = {}
            end
            objs[k] = self:getObjectID(v)
        end
    end

    local code = dump({fields, #obj, objs})

    self.codeMap[id] = code
    return id
end

---@param writter fun(id: integer, code: string): boolean
---@param reader  fun(id: integer): string?
function mt:bind(writter, reader)
    setmt(self.codeMap, {
        __newindex = function (t, id, code)
            local suc = writter(id, code)
            if not suc then
                rawset(t, id, code)
            end
        end,
        __index = function (_, id)
            return reader(id)
        end
    })
end

---@param t table
function mt:exclude(t)
    self.excludes[t] = true
    return self
end

---@return table
function mt:entry()
    local entryID = self:getObjectID(self.source)

    local codeMap = self.codeMap
    local refMap  = self.refMap
    local instMap = self.instMap
    local tableID = self.tableID
    ---@type table<table, integer>
    local idMap   = {}
    ---@type table<table, table[]>
    local infoMap = setmt({}, {
        __mode = 'v',
        __index = function (map, t)
            local id   = idMap[t]
            local code = codeMap[id]
            if not code then
                return nil
            end
            local f = load(code)
            if not f then
                return nil
            end
            --if sbyte(code, 1, 1) ~= 27 then
            --    codeMap[id] = sdump(f, true)
            --end
            local info = f()
            map[t] = info
            return info
        end
    })

    local lazyload = {
        ref = refMap,
        __index = function(t, k)
            local info = infoMap[t]
            if not info then
                return nil
            end
            local fields = info[1]

            local keyID = k

            local v = fields[keyID]
            if v ~= nil then
                return v
            end

            local refs = info[3]
            if not refs then
                return nil
            end

            local ref = refs[keyID]
            if not ref then
                return nil
            end

            return instMap[ref]
        end,
        __newindex = function(t, k, v)
            local info   = infoMap[t]
            local fields = info and info[1] or {}
            local len    = info and info[2] or 0
            local objs   = info and info[3]
            fields[k]    = nil
            if objs then
                objs[k] = nil
            end
            if v ~= nil then
                local tp = type(v)
                if tp == 'string' or tp == 'number' or tp == 'boolean' then
                    fields[k] = v
                else
                    if not objs then
                        objs = {}
                    end
                    local id = refMap[v] or idMap[v]
                    if not id then
                        id = tableID
                        refMap[v] = id -- 新赋值的对象一定会被引用住
                        instMap[id] = v
                        tableID = tableID + 1
                    end
                    objs[k] = id
                end
            end
            info = { fields, len, objs }
            local id = idMap[t]
            local code = dump(info)
            infoMap[id] = nil
            codeMap[id] = nil
            codeMap[id] = code
        end,
        __len = function (t)
            local info = infoMap[t]
            if not info then
                return 0
            end
            return info[2]
        end,
        __pairs = function (t)
            local info = infoMap[t]
            if not info then
                return DUMMY
            end
            local fields = info[1]
            local objs   = info[3]
            local keys   = {}
            for k in pairs(fields) do
                keys[#keys+1] = k
            end
            if objs then
                for k in pairs(objs) do
                    keys[#keys+1] = k
                end
            end
            local i = 0
            return function()
                i = i + 1
                local k = keys[i]
                return k, t[k]
            end
        end,
    }

    setmt(idMap, { __mode = 'k' })

    setmt(instMap, {
        __mode  = 'v',
        __index = function (map, id)
            local inst  = {}
            idMap[inst] = id
            map[id]     = inst

            return setmt(inst, lazyload)
        end,
    })

    local entry = instMap[entryID] --[[@as table]]

    self.source = nil
    self.dumpMark = nil

    return entry
end

---@class lazytable
local m = {}

---@param t table
---@param writter? fun(id: integer, code: string): boolean
---@param reader?  fun(id: integer): string?
---@return lazytable.builder
function m.build(t, writter, reader)
    local builder = setmt({
        source     = t,
        codeMap    = {},
        refMap     = {},
        instMap    = {},
        dumpMark   = {},
        excludes   = setmt({}, { __mode = 'k' }),
    }, mt)

    if writter and reader then
        builder:bind(writter, reader)
    end

    return builder
end

return m