forked from Benjamin-Dobell/ge_tts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJson.ttslua
263 lines (209 loc) · 8.74 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
-- JSON encoding of Color presently fails due to a bug in Color. Fortunately, we can patch Color to fix it.
require('ge_tts.GlobalPatches')
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')
---@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 encoded as the zeroth element. 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: ge_tts__JsonValue): void
---@field onError fun(message: string): void
---@field charactersPerChunk nil | number @Default 2048 (2 KiB)
---@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 cancelled = 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
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
array[0] = 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 cancelled then
return nil
end
Coroutine.yieldFrames(framesBetweenChunks, function(message)
if not cancelled 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 cancelled then
options.onCompletion(result)
end
end)
return function()
cancelled = true
end
end
local decode = LunaJsonDecoder()
---@overload fun(json: string): ge_tts__JsonValue
---@param json string
---@param options nil | ge_tts__Json_DecodeOptions
---@return ge_tts__JsonValue
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 json ge_tts__JsonValue
---@return string
function Json.encode(value)
return encode(value, Json.null())
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