You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

390 regels
9.4 KiB

  1. R"(
  2. --
  3. -- json.lua
  4. --
  5. -- Copyright (c) 2020 rxi
  6. --
  7. -- Permission is hereby granted, free of charge, to any person obtaining a copy of
  8. -- this software and associated documentation files (the "Software"), to deal in
  9. -- the Software without restriction, including without limitation the rights to
  10. -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  11. -- of the Software, and to permit persons to whom the Software is furnished to do
  12. -- so, subject to the following conditions:
  13. --
  14. -- The above copyright notice and this permission notice shall be included in all
  15. -- copies or substantial portions of the Software.
  16. --
  17. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. -- SOFTWARE.
  24. --
  25. local json = { _version = "0.1.2" }
  26. -------------------------------------------------------------------------------
  27. -- Encode
  28. -------------------------------------------------------------------------------
  29. local encode
  30. local escape_char_map = {
  31. [ "\\" ] = "\\",
  32. [ "\"" ] = "\"",
  33. [ "\b" ] = "b",
  34. [ "\f" ] = "f",
  35. [ "\n" ] = "n",
  36. [ "\r" ] = "r",
  37. [ "\t" ] = "t",
  38. }
  39. local escape_char_map_inv = { [ "/" ] = "/" }
  40. for k, v in pairs(escape_char_map) do
  41. escape_char_map_inv[v] = k
  42. end
  43. local function escape_char(c)
  44. return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
  45. end
  46. local function encode_nil(val)
  47. return "null"
  48. end
  49. local function encode_table(val, stack)
  50. local res = {}
  51. stack = stack or {}
  52. -- Circular reference?
  53. if stack[val] then error("circular reference") end
  54. stack[val] = true
  55. if rawget(val, 1) ~= nil or next(val) == nil then
  56. -- Treat as array -- check keys are valid and it is not sparse
  57. local n = 0
  58. for k in pairs(val) do
  59. if type(k) ~= "number" then
  60. error("invalid table: mixed or invalid key types")
  61. end
  62. n = n + 1
  63. end
  64. if n ~= #val then
  65. error("invalid table: sparse array")
  66. end
  67. -- Encode
  68. for i, v in ipairs(val) do
  69. table.insert(res, encode(v, stack))
  70. end
  71. stack[val] = nil
  72. return "[" .. table.concat(res, ",") .. "]"
  73. else
  74. -- Treat as an object
  75. for k, v in pairs(val) do
  76. if type(k) ~= "string" then
  77. error("invalid table: mixed or invalid key types")
  78. end
  79. table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
  80. end
  81. stack[val] = nil
  82. return "{" .. table.concat(res, ",") .. "}"
  83. end
  84. end
  85. local function encode_string(val)
  86. return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
  87. end
  88. local function encode_number(val)
  89. -- Check for NaN, -inf and inf
  90. if val ~= val or val <= -math.huge or val >= math.huge then
  91. error("unexpected number value '" .. tostring(val) .. "'")
  92. end
  93. return string.format("%.14g", val)
  94. end
  95. local type_func_map = {
  96. [ "nil" ] = encode_nil,
  97. [ "table" ] = encode_table,
  98. [ "string" ] = encode_string,
  99. [ "number" ] = encode_number,
  100. [ "boolean" ] = tostring,
  101. }
  102. encode = function(val, stack)
  103. local t = type(val)
  104. local f = type_func_map[t]
  105. if f then
  106. return f(val, stack)
  107. end
  108. error("unexpected type '" .. t .. "'")
  109. end
  110. function json.encode(val)
  111. return ( encode(val) )
  112. end
  113. -------------------------------------------------------------------------------
  114. -- Decode
  115. -------------------------------------------------------------------------------
  116. local parse
  117. local function create_set(...)
  118. local res = {}
  119. for i = 1, select("#", ...) do
  120. res[ select(i, ...) ] = true
  121. end
  122. return res
  123. end
  124. local space_chars = create_set(" ", "\t", "\r", "\n")
  125. local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
  126. local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
  127. local literals = create_set("true", "false", "null")
  128. local literal_map = {
  129. [ "true" ] = true,
  130. [ "false" ] = false,
  131. [ "null" ] = nil,
  132. }
  133. local function next_char(str, idx, set, negate)
  134. for i = idx, #str do
  135. if set[str:sub(i, i)] ~= negate then
  136. return i
  137. end
  138. end
  139. return #str + 1
  140. end
  141. local function decode_error(str, idx, msg)
  142. local line_count = 1
  143. local col_count = 1
  144. for i = 1, idx - 1 do
  145. col_count = col_count + 1
  146. if str:sub(i, i) == "\n" then
  147. line_count = line_count + 1
  148. col_count = 1
  149. end
  150. end
  151. error( string.format("%s at line %d col %d", msg, line_count, col_count) )
  152. end
  153. local function codepoint_to_utf8(n)
  154. -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
  155. local f = math.floor
  156. if n <= 0x7f then
  157. return string.char(n)
  158. elseif n <= 0x7ff then
  159. return string.char(f(n / 64) + 192, n % 64 + 128)
  160. elseif n <= 0xffff then
  161. return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
  162. elseif n <= 0x10ffff then
  163. return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
  164. f(n % 4096 / 64) + 128, n % 64 + 128)
  165. end
  166. error( string.format("invalid unicode codepoint '%x'", n) )
  167. end
  168. local function parse_unicode_escape(s)
  169. local n1 = tonumber( s:sub(1, 4), 16 )
  170. local n2 = tonumber( s:sub(7, 10), 16 )
  171. -- Surrogate pair?
  172. if n2 then
  173. return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
  174. else
  175. return codepoint_to_utf8(n1)
  176. end
  177. end
  178. local function parse_string(str, i)
  179. local res = ""
  180. local j = i + 1
  181. local k = j
  182. while j <= #str do
  183. local x = str:byte(j)
  184. if x < 32 then
  185. decode_error(str, j, "control character in string")
  186. elseif x == 92 then -- `\`: Escape
  187. res = res .. str:sub(k, j - 1)
  188. j = j + 1
  189. local c = str:sub(j, j)
  190. if c == "u" then
  191. local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
  192. or str:match("^%x%x%x%x", j + 1)
  193. or decode_error(str, j - 1, "invalid unicode escape in string")
  194. res = res .. parse_unicode_escape(hex)
  195. j = j + #hex
  196. else
  197. if not escape_chars[c] then
  198. decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
  199. end
  200. res = res .. escape_char_map_inv[c]
  201. end
  202. k = j + 1
  203. elseif x == 34 then -- `"`: End of string
  204. res = res .. str:sub(k, j - 1)
  205. return res, j + 1
  206. end
  207. j = j + 1
  208. end
  209. decode_error(str, i, "expected closing quote for string")
  210. end
  211. local function parse_number(str, i)
  212. local x = next_char(str, i, delim_chars)
  213. local s = str:sub(i, x - 1)
  214. local n = tonumber(s)
  215. if not n then
  216. decode_error(str, i, "invalid number '" .. s .. "'")
  217. end
  218. return n, x
  219. end
  220. local function parse_literal(str, i)
  221. local x = next_char(str, i, delim_chars)
  222. local word = str:sub(i, x - 1)
  223. if not literals[word] then
  224. decode_error(str, i, "invalid literal '" .. word .. "'")
  225. end
  226. return literal_map[word], x
  227. end
  228. local function parse_array(str, i)
  229. local res = {}
  230. local n = 1
  231. i = i + 1
  232. while 1 do
  233. local x
  234. i = next_char(str, i, space_chars, true)
  235. -- Empty / end of array?
  236. if str:sub(i, i) == "]" then
  237. i = i + 1
  238. break
  239. end
  240. -- Read token
  241. x, i = parse(str, i)
  242. res[n] = x
  243. n = n + 1
  244. -- Next token
  245. i = next_char(str, i, space_chars, true)
  246. local chr = str:sub(i, i)
  247. i = i + 1
  248. if chr == "]" then break end
  249. if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
  250. end
  251. return res, i
  252. end
  253. local function parse_object(str, i)
  254. local res = {}
  255. i = i + 1
  256. while 1 do
  257. local key, val
  258. i = next_char(str, i, space_chars, true)
  259. -- Empty / end of object?
  260. if str:sub(i, i) == "}" then
  261. i = i + 1
  262. break
  263. end
  264. -- Read key
  265. if str:sub(i, i) ~= '"' then
  266. decode_error(str, i, "expected string for key")
  267. end
  268. key, i = parse(str, i)
  269. -- Read ':' delimiter
  270. i = next_char(str, i, space_chars, true)
  271. if str:sub(i, i) ~= ":" then
  272. decode_error(str, i, "expected ':' after key")
  273. end
  274. i = next_char(str, i + 1, space_chars, true)
  275. -- Read value
  276. val, i = parse(str, i)
  277. -- Set
  278. res[key] = val
  279. -- Next token
  280. i = next_char(str, i, space_chars, true)
  281. local chr = str:sub(i, i)
  282. i = i + 1
  283. if chr == "}" then break end
  284. if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
  285. end
  286. return res, i
  287. end
  288. local char_func_map = {
  289. [ '"' ] = parse_string,
  290. [ "0" ] = parse_number,
  291. [ "1" ] = parse_number,
  292. [ "2" ] = parse_number,
  293. [ "3" ] = parse_number,
  294. [ "4" ] = parse_number,
  295. [ "5" ] = parse_number,
  296. [ "6" ] = parse_number,
  297. [ "7" ] = parse_number,
  298. [ "8" ] = parse_number,
  299. [ "9" ] = parse_number,
  300. [ "-" ] = parse_number,
  301. [ "t" ] = parse_literal,
  302. [ "f" ] = parse_literal,
  303. [ "n" ] = parse_literal,
  304. [ "[" ] = parse_array,
  305. [ "{" ] = parse_object,
  306. }
  307. parse = function(str, idx)
  308. local chr = str:sub(idx, idx)
  309. local f = char_func_map[chr]
  310. if f then
  311. return f(str, idx)
  312. end
  313. decode_error(str, idx, "unexpected character '" .. chr .. "'")
  314. end
  315. function json.decode(str)
  316. if type(str) ~= "string" then
  317. error("expected argument of type string, got " .. type(str))
  318. end
  319. local res, idx = parse(str, next_char(str, 1, space_chars, true))
  320. idx = next_char(str, idx, space_chars, true)
  321. if idx <= #str then
  322. decode_error(str, idx, "trailing garbage")
  323. end
  324. return res
  325. end
  326. return json
  327. )"