-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathJson.ttslua
executable file
·363 lines (288 loc) · 12.1 KB
/
Json.ttslua
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
354
355
356
357
358
359
360
361
362
363
require('ge_tts.License')
local License = require('ge_tts.License')
if Color then
-- JSON encoding of Color presently fails due to a bug in Color. Fortunately, we can patch Color to fix it.
require('ge_tts.GlobalPatches')
end
local Coroutine = require('ge_tts.Coroutine')
local TableUtils = require('ge_tts.TableUtils')
local LunaJsonDecoder = require('ge_tts.lunajson.decoder')
local LunaJsonEncoder = require('ge_tts.lunajson.encoder')
local LunaJsonSax = require('ge_tts.lunajson.sax')
-- This license applies to lunajson. Do *not* assume it extends to the mod!
local lunajsonLicense = [[The MIT License (MIT)
Copyright (c) 2015-2017 Shunsuke Shimizu (grafi)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.]]
License.add("lunajson", lunajsonLicense)
---@class ge_tts__JsonNull
local NULL = setmetatable({}, {
__index = {},
__newindex = function() error("Attempt to modify JSON.null()") end,
__metatable = false
})
---@class ge_tts__Json
local Json = {}
---@return ge_tts__JsonNull
function Json.null()
return NULL
end
---@alias ge_tts__JsonObject table<string, ge_tts__JsonValue>
---@alias ge_tts__JsonArray ge_tts__JsonValue[]
---@alias ge_tts__JsonContainer ge_tts__JsonObject | ge_tts__JsonArray
---@alias ge_tts__JsonValue ge_tts__JsonContainer | number | string | boolean | nil | ge_tts__JsonNull
---@alias __ge_tts__JsonNodeTypeObject 0
---@alias __ge_tts__JsonNodeTypeArray 1
---@alias __ge_tts__JsonNodeTypeKey 2
---@type __ge_tts__JsonNodeTypeObject
local NODE_OBJECT = 0
---@type __ge_tts__JsonNodeTypeArray
local NODE_ARRAY = 1
---@type __ge_tts__JsonNodeTypeKey
local NODE_KEY = 2
---@alias __ge_tts__JsonNodeType __ge_tts__JsonNodeTypeObject | __ge_tts__JsonNodeTypeArray | __ge_tts__JsonNodeTypeKey
---@alias __ge_tts__JsonObjectNode {[1]: __ge_tts__JsonNodeTypeObject, [2]: ge_tts__JsonObject}
---@alias __ge_tts__JsonArrayNode {[1]: __ge_tts__JsonNodeTypeArray, [2]: ge_tts__JsonArray, [3]: number}
---@alias __ge_tts__JsonKeyNode {[1]: __ge_tts__JsonNodeTypeKey, [2]: string }
---@alias __ge_tts__JsonNode __ge_tts__JsonObjectNode | __ge_tts__JsonArrayNode | __ge_tts__JsonKeyNode
---@shape ge_tts__Json_DecodeOptions
---@field encodeArrayLength nil | boolean @Default false. When true, array lengths are written to an `n` field on the array (i.e. std__Packed). Thus an empty array can be discerned from an empty table.
---@field nullIdentification nil | boolean @Default true. When true, null values in an array/object are represented by JSON.null() rather than being omitted.
---@shape ge_tts__Json_DecodeAsyncOptions : ge_tts__Json_DecodeOptions
---@field onCompletion fun(data: any): void
---@field onError fun(message: string): void
---@field charactersPerChunk nil | number @Default 2048 (2 KiB)
---@field framesBetweenChunks nil | number @Default 1
---@shape ge_tts__Json_EncodeAsyncOptions
---@field onCompletion fun(json: string): void
---@field onError fun(message: string): void
---@field componentsPerChunk nil | number @Default 128
---@field framesBetweenChunks nil | number @Default 1
---@type ge_tts__Json_DecodeOptions
local defaultDecodeOptions = {
encodeArrayLength = false,
nullIdentification = true,
}
--- Sets the default decoding options used by decode and decodeAsync when called with options omitted.
---@param decodeOptions ge_tts__Json_DecodeOptions
function Json.setDefaultDecodeOptions(decodeOptions)
defaultDecodeOptions = decodeOptions
end
--- Parses JSON in a pseudo-async fashion using co-operative multi-tasking (i.e. coroutines).
---
--- The parser will only do a limited amount of work each frame before handing off processing back to TTS, thus we
--- don't freeze the game when parsing large JSON.
---
--- Return value is a function that can be called to cancel decoding if it is yet to complete.
---@param json string
---@param options ge_tts__Json_DecodeAsyncOptions
---@return fun(): void
function Json.decodeAsync(json, options)
local canceled = false
options = TableUtils.merge(--[[---@type ge_tts__Json_DecodeAsyncOptions]] defaultDecodeOptions, options)
Coroutine.start(function()
---@type __ge_tts__JsonNode[]
local stack = {}
---@type nil | __ge_tts__JsonNode
local currentNode
---@type ge_tts__JsonValue
local result
---@param value ge_tts__JsonValue
local function addValue(value)
if currentNode then
local nodeType = (--[[---@not nil]] currentNode)[1]
if value == nil and options.nullIdentification then
value = Json.null()
end
if nodeType == NODE_KEY then
local key = (--[[---@type __ge_tts__JsonKeyNode]] currentNode)[2]
local parentNode = --[[---@type __ge_tts__JsonObjectNode]] table.remove(stack)
local parentObject = parentNode[2]
parentObject[key] = value
currentNode = parentNode
elseif nodeType == NODE_ARRAY then
local arrayNode = --[[---@type __ge_tts__JsonArrayNode]] currentNode
local array = arrayNode[2]
arrayNode[3] = arrayNode[3] + 1 -- Update length
array[arrayNode[3]] = value
end
else
result = value
end
end
---@type lunajson__SaxHandler
local handler = {
startobject = function()
if currentNode then
table.insert(stack, --[[---@not nil]] currentNode)
end
currentNode = {NODE_OBJECT , {}}
end,
---@param key string
key = function(key)
table.insert(stack, --[[---@not nil]] currentNode)
currentNode = {NODE_KEY, key}
end,
endobject = function()
local objectNode = (--[[---@type __ge_tts__JsonObjectNode]] currentNode)
currentNode = table.remove(stack)
addValue(objectNode[2])
end,
startarray = function()
if currentNode then
table.insert(stack, --[[---@not nil]] currentNode)
end
currentNode = {NODE_ARRAY , {}, 0}
end,
endarray = function()
local objectNode = (--[[---@type __ge_tts__JsonArrayNode]] currentNode)
local array = objectNode[2]
currentNode = table.remove(stack)
if options.encodeArrayLength then
(--[[---@type std__Packed<ge_tts__JsonValue>]] array).n = objectNode[3]
end
addValue(array)
end,
string = addValue,
number = addValue,
boolean = addValue,
null = function()
addValue(nil)
end,
}
---@type number
local charactersPerChunk = 0
if options.charactersPerChunk then
charactersPerChunk = --[[---@not nil]] options.charactersPerChunk
end
if charactersPerChunk <= 0 then
charactersPerChunk = 2048
end
---@type number
local framesBetweenChunks
if options.framesBetweenChunks and framesBetweenChunks > 0 then
framesBetweenChunks = --[[---@not nil]] options.framesBetweenChunks
else
framesBetweenChunks = 1
end
local offset = 1
local length = #json
local function feed()
local characterCount = math.min(length - offset + 1, charactersPerChunk)
if characterCount == 0 or canceled then
return nil
end
Coroutine.yieldFrames(framesBetweenChunks, function(message)
if not canceled then
options.onError(message)
end
end)
local nextOffset = offset + characterCount
local substring = json:sub(offset, nextOffset - 1)
offset = nextOffset
return substring
end
local parser = --[[---@type {run: fun(): void}]] LunaJsonSax.newparser(feed, handler)
parser.run()
if not canceled then
options.onCompletion(result)
end
end)
return function()
canceled = true
end
end
local decode = LunaJsonDecoder()
---@overload fun(json: string): any
---@param json string
---@param options nil | ge_tts__Json_DecodeOptions
---@return any
function Json.decode(json, options)
local decodeOptions = TableUtils.merge(defaultDecodeOptions, --[[---@not nil]] options or {})
local nullValue = decodeOptions.nullIdentification and Json.null() or nil
return (decode(json, 0, nullValue, decodeOptions.encodeArrayLength or false))
end
local encode = LunaJsonEncoder()
---@param value any
---@return string
function Json.encode(value)
return encode(value, Json.null())
end
---@param value any
---@param options ge_tts__Json_EncodeAsyncOptions
---@return fun(): void
function Json.encodeAsync(value, options)
local canceled = false
Coroutine.start(function()
local asyncEncode = LunaJsonEncoder()
local concat = table.concat
---@param builder string[]
---@param nextIndex number
---@return string[], number
local function replacer(builder, nextIndex)
return { concat(builder) }, 2
end
---@type lunajson__GenerateValueEncode
local generateEncode = function(nullv, dispatcher, push, replaceBuilder)
local componentCount = 0
local chunkSize = options.componentsPerChunk or 128
local waitFrames = options.framesBetweenChunks or 1
---@param v
return function(v)
if canceled then
return
end
if v == nullv then
push('null')
else
dispatcher[--[[---@not 'nil' | 'function' | 'thread' | 'userdata']] type(v)](v)
end
componentCount = componentCount + 1
if componentCount >= chunkSize then
componentCount = 0
replaceBuilder(replacer)
Coroutine.yieldFrames(waitFrames, function(message)
if not canceled then
options.onError(message)
end
end)
end
end
end
local result = asyncEncode(value, Json.null(), generateEncode)
if not canceled then
options.onCompletion(result)
end
end)
return function()
canceled = true
end
end
--- Fills gaps (up to the specified length) in sparseArray with Json.null(), then returns it.
---@generic T
---@generic N : number
---@param sparseArray table<N, nil | T>
---@param length number
---@return (T | ge_tts__JsonNull)[]
function Json.nullFillSparseArray(sparseArray, length)
for i = 1, length do
if type((--[[---@type T[] ]] sparseArray)[i]) == 'nil' then
(--[[---@type (T | ge_tts__JsonNull)[] ]] sparseArray)[i] = Json.null()
end
end
return --[[---@type (T | ge_tts__JsonNull)[] ]] sparseArray
end
return Json