becd295d55590e4757736c8a9cc1b4c16e7d834f
[prosody.git] / util / json.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local type = type;
10 local t_insert, t_concat, t_remove, t_sort = table.insert, table.concat, table.remove, table.sort;
11 local s_char = string.char;
12 local tostring, tonumber = tostring, tonumber;
13 local pairs, ipairs = pairs, ipairs;
14 local next = next;
15 local error = error;
16 local getmetatable, setmetatable = getmetatable, setmetatable;
17 local print = print;
18
19 local has_array, array = pcall(require, "util.array");
20 local array_mt = has_array and getmetatable(array()) or {};
21
22 --module("json")
23 local json = {};
24
25 local null = setmetatable({}, { __tostring = function() return "null"; end; });
26 json.null = null;
27
28 local escapes = {
29         ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b",
30         ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"};
31 local unescapes = {
32         ["\""] = "\"", ["\\"] = "\\", ["/"] = "/",
33         b = "\b", f = "\f", n = "\n", r = "\r", t = "\t"};
34 for i=0,31 do
35         local ch = s_char(i);
36         if not escapes[ch] then escapes[ch] = ("\\u%.4X"):format(i); end
37 end
38
39 local function codepoint_to_utf8(code)
40         if code < 0x80 then return s_char(code); end
41         local bits0_6 = code % 64;
42         if code < 0x800 then
43                 local bits6_5 = (code - bits0_6) / 64;
44                 return s_char(0x80 + 0x40 + bits6_5, 0x80 + bits0_6);
45         end
46         local bits0_12 = code % 4096;
47         local bits6_6 = (bits0_12 - bits0_6) / 64;
48         local bits12_4 = (code - bits0_12) / 4096;
49         return s_char(0x80 + 0x40 + 0x20 + bits12_4, 0x80 + bits6_6, 0x80 + bits0_6);
50 end
51
52 local valid_types = {
53         number  = true,
54         string  = true,
55         table   = true,
56         boolean = true
57 };
58 local special_keys = {
59         __array = true;
60         __hash  = true;
61 };
62
63 local simplesave, tablesave, arraysave, stringsave;
64
65 function stringsave(o, buffer)
66         -- FIXME do proper utf-8 and binary data detection
67         t_insert(buffer, "\""..(o:gsub(".", escapes)).."\"");
68 end
69
70 function arraysave(o, buffer)
71         t_insert(buffer, "[");
72         if next(o) then
73                 for i,v in ipairs(o) do
74                         simplesave(v, buffer);
75                         t_insert(buffer, ",");
76                 end
77                 t_remove(buffer);
78         end
79         t_insert(buffer, "]");
80 end
81
82 function tablesave(o, buffer)
83         local __array = {};
84         local __hash = {};
85         local hash = {};
86         for i,v in ipairs(o) do
87                 __array[i] = v;
88         end
89         for k,v in pairs(o) do
90                 local ktype, vtype = type(k), type(v);
91                 if valid_types[vtype] or v == null then
92                         if ktype == "string" and not special_keys[k] then
93                                 hash[k] = v;
94                         elseif (valid_types[ktype] or k == null) and __array[k] == nil then
95                                 __hash[k] = v;
96                         end
97                 end
98         end
99         if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then
100                 t_insert(buffer, "{");
101                 local mark = #buffer;
102                 if buffer.ordered then
103                         local keys = {};
104                         for k in pairs(hash) do
105                                 t_insert(keys, k);
106                         end
107                         t_sort(keys);
108                         for _,k in ipairs(keys) do
109                                 stringsave(k, buffer);
110                                 t_insert(buffer, ":");
111                                 simplesave(hash[k], buffer);
112                                 t_insert(buffer, ",");
113                         end
114                 else
115                         for k,v in pairs(hash) do
116                                 stringsave(k, buffer);
117                                 t_insert(buffer, ":");
118                                 simplesave(v, buffer);
119                                 t_insert(buffer, ",");
120                         end
121                 end
122                 if next(__hash) ~= nil then
123                         t_insert(buffer, "\"__hash\":[");
124                         for k,v in pairs(__hash) do
125                                 simplesave(k, buffer);
126                                 t_insert(buffer, ",");
127                                 simplesave(v, buffer);
128                                 t_insert(buffer, ",");
129                         end
130                         t_remove(buffer);
131                         t_insert(buffer, "]");
132                         t_insert(buffer, ",");
133                 end
134                 if next(__array) then
135                         t_insert(buffer, "\"__array\":");
136                         arraysave(__array, buffer);
137                         t_insert(buffer, ",");
138                 end
139                 if mark ~= #buffer then t_remove(buffer); end
140                 t_insert(buffer, "}");
141         else
142                 arraysave(__array, buffer);
143         end
144 end
145
146 function simplesave(o, buffer)
147         local t = type(o);
148         if t == "number" then
149                 t_insert(buffer, tostring(o));
150         elseif t == "string" then
151                 stringsave(o, buffer);
152         elseif t == "table" then
153                 local mt = getmetatable(o);
154                 if mt == array_mt then
155                         arraysave(o, buffer);
156                 else
157                         tablesave(o, buffer);
158                 end
159         elseif t == "boolean" then
160                 t_insert(buffer, (o and "true" or "false"));
161         else
162                 t_insert(buffer, "null");
163         end
164 end
165
166 function json.encode(obj)
167         local t = {};
168         simplesave(obj, t);
169         return t_concat(t);
170 end
171 function json.encode_ordered(obj)
172         local t = { ordered = true };
173         simplesave(obj, t);
174         return t_concat(t);
175 end
176 function json.encode_array(obj)
177         local t = {};
178         arraysave(obj, t);
179         return t_concat(t);
180 end
181
182 -----------------------------------
183
184
185 local function _skip_whitespace(json, index)
186         return json:find("[^ \t\r\n]", index) or index; -- no need to check \r\n, we converted those to \t
187 end
188 local function _fixobject(obj)
189         local __array = obj.__array;
190         if __array then
191                 obj.__array = nil;
192                 for i,v in ipairs(__array) do
193                         t_insert(obj, v);
194                 end
195         end
196         local __hash = obj.__hash;
197         if __hash then
198                 obj.__hash = nil;
199                 local k;
200                 for i,v in ipairs(__hash) do
201                         if k ~= nil then
202                                 obj[k] = v; k = nil;
203                         else
204                                 k = v;
205                         end
206                 end
207         end
208         return obj;
209 end
210 local _readvalue, _readstring;
211 local function _readobject(json, index)
212         local o = {};
213         while true do
214                 local key, val;
215                 index = _skip_whitespace(json, index + 1);
216                 if json:byte(index) ~= 0x22 then -- "\""
217                         if json:byte(index) == 0x7d then return o, index + 1; end -- "}"
218                         return nil, "key expected";
219                 end
220                 key, index = _readstring(json, index);
221                 if key == nil then return nil, index; end
222                 index = _skip_whitespace(json, index);
223                 if json:byte(index) ~= 0x3a then return nil, "colon expected"; end -- ":"
224                 val, index = _readvalue(json, index + 1);
225                 if val == nil then return nil, index; end
226                 o[key] = val;
227                 index = _skip_whitespace(json, index);
228                 local b = json:byte(index);
229                 if b == 0x7d then return _fixobject(o), index + 1; end -- "}"
230                 if b ~= 0x2c then return nil, "object eof"; end -- ","
231         end
232 end
233 local function _readarray(json, index)
234         local a = {};
235         local oindex = index;
236         while true do
237                 local val;
238                 val, index = _readvalue(json, index + 1);
239                 if val == nil then
240                         if json:byte(oindex + 1) == 0x5d then return setmetatable(a, array_mt), oindex + 2; end -- "]"
241                         return val, index;
242                 end
243                 t_insert(a, val);
244                 index = _skip_whitespace(json, index);
245                 local b = json:byte(index);
246                 if b == 0x5d then return setmetatable(a, array_mt), index + 1; end -- "]"
247                 if b ~= 0x2c then return nil, "array eof"; end -- ","
248         end
249 end
250 local _unescape_error;
251 local function _unescape_surrogate_func(x)
252         local lead, trail = tonumber(x:sub(3, 6), 16), tonumber(x:sub(9, 12), 16);
253         local codepoint = lead * 0x400 + trail - 0x35FDC00;
254         local a = codepoint % 64;
255         codepoint = (codepoint - a) / 64;
256         local b = codepoint % 64;
257         codepoint = (codepoint - b) / 64;
258         local c = codepoint % 64;
259         codepoint = (codepoint - c) / 64;
260         return s_char(0xF0 + codepoint, 0x80 + c, 0x80 + b, 0x80 + a);
261 end
262 local function _unescape_func(x)
263         x = x:match("%x%x%x%x", 3);
264         if x then
265                 --if x >= 0xD800 and x <= 0xDFFF then _unescape_error = true; end -- bad surrogate pair
266                 return codepoint_to_utf8(tonumber(x, 16));
267         end
268         _unescape_error = true;
269 end
270 function _readstring(json, index)
271         index = index + 1;
272         local endindex = json:find("\"", index, true);
273         if endindex then
274                 local s = json:sub(index, endindex - 1);
275                 --if s:find("[%z-\31]") then return nil, "control char in string"; end
276                 -- FIXME handle control characters
277                 _unescape_error = nil;
278                 --s = s:gsub("\\u[dD][89abAB]%x%x\\u[dD][cdefCDEF]%x%x", _unescape_surrogate_func);
279                 -- FIXME handle escapes beyond BMP
280                 s = s:gsub("\\u.?.?.?.?", _unescape_func);
281                 if _unescape_error then return nil, "invalid escape"; end
282                 return s, endindex + 1;
283         end
284         return nil, "string eof";
285 end
286 local function _readnumber(json, index)
287         local m = json:match("[0-9%.%-eE%+]+", index); -- FIXME do strict checking
288         return tonumber(m), index + #m;
289 end
290 local function _readnull(json, index)
291         local a, b, c = json:byte(index + 1, index + 3);
292         if a == 0x75 and b == 0x6c and c == 0x6c then
293                 return null, index + 4;
294         end
295         return nil, "null parse failed";
296 end
297 local function _readtrue(json, index)
298         local a, b, c = json:byte(index + 1, index + 3);
299         if a == 0x72 and b == 0x75 and c == 0x65 then
300                 return true, index + 4;
301         end
302         return nil, "true parse failed";
303 end
304 local function _readfalse(json, index)
305         local a, b, c, d = json:byte(index + 1, index + 4);
306         if a == 0x61 and b == 0x6c and c == 0x73 and d == 0x65 then
307                 return false, index + 5;
308         end
309         return nil, "false parse failed";
310 end
311 function _readvalue(json, index)
312         index = _skip_whitespace(json, index);
313         local b = json:byte(index);
314         -- TODO try table lookup instead of if-else?
315         if b == 0x7B then -- "{"
316                 return _readobject(json, index);
317         elseif b == 0x5B then -- "["
318                 return _readarray(json, index);
319         elseif b == 0x22 then -- "\""
320                 return _readstring(json, index);
321         elseif b ~= nil and b >= 0x30 and b <= 0x39 or b == 0x2d then -- "0"-"9" or "-"
322                 return _readnumber(json, index);
323         elseif b == 0x6e then -- "n"
324                 return _readnull(json, index);
325         elseif b == 0x74 then -- "t"
326                 return _readtrue(json, index);
327         elseif b == 0x66 then -- "f"
328                 return _readfalse(json, index);
329         else
330                 return nil, "value expected";
331         end
332 end
333 local first_escape = {
334         ["\\\""] = "\\u0022";
335         ["\\\\"] = "\\u005c";
336         ["\\/" ] = "\\u002f";
337         ["\\b" ] = "\\u0008";
338         ["\\f" ] = "\\u000C";
339         ["\\n" ] = "\\u000A";
340         ["\\r" ] = "\\u000D";
341         ["\\t" ] = "\\u0009";
342         ["\\u" ] = "\\u";
343 };
344
345 function json.decode(json)
346         json = json:gsub("\\.", first_escape) -- get rid of all escapes except \uXXXX, making string parsing much simpler
347                 --:gsub("[\r\n]", "\t"); -- \r\n\t are equivalent, we care about none of them, and none of them can be in strings
348
349         -- TODO do encoding verification
350
351         local val, index = _readvalue(json, 1);
352         if val == nil then return val, index; end
353         if json:find("[^ \t\r\n]", index) then return nil, "garbage at eof"; end
354
355         return val;
356 end
357
358 function json.test(object)
359         local encoded = json.encode(object);
360         local decoded = json.decode(encoded);
361         local recoded = json.encode(decoded);
362         if encoded ~= recoded then
363                 print("FAILED");
364                 print("encoded:", encoded);
365                 print("recoded:", recoded);
366         else
367                 print(encoded);
368         end
369         return encoded == recoded;
370 end
371
372 return json;