rev |
line source |
jbe@121
|
1 #include <lua.h>
|
jbe@121
|
2 #include <lauxlib.h>
|
jbe@122
|
3 #include <stdlib.h>
|
jbe@121
|
4 #include <string.h>
|
jbe@154
|
5 #include <math.h>
|
jbe@121
|
6
|
jbe@144
|
7 // maximum number of nested JSON values (objects and arrays):
|
jbe@150
|
8 // NOTE: The Lua reference states that the stack may typically contain at least
|
jbe@150
|
9 // "a few thousand elements". Since every nested level consumes
|
jbe@150
|
10 // 3 elements on the Lua stack (the object/array, its shadow table,
|
jbe@150
|
11 // a string key or a placeholder), we limit the number of nested levels
|
jbe@150
|
12 // to 500. If a stack overflow would still happen in the import function,
|
jbe@150
|
13 // this is detected nevertheless and an error is thrown (instead of
|
jbe@150
|
14 // returning nil and an error string).
|
jbe@150
|
15 #define JSON_MAXDEPTH 500
|
jbe@142
|
16
|
jbe@155
|
17 // generate dummy memory addresses that represents null values:
|
jbe@155
|
18 char json_nullmark;
|
jbe@155
|
19 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
|
jbe@155
|
20 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
|
jbe@155
|
21
|
jbe@144
|
22 // macros for usage of Lua registry:
|
jbe@144
|
23 #define JSON_REGENT char
|
jbe@145
|
24 #define JSON_REGPOINTER void *
|
jbe@145
|
25 #define json_regpointer(x) (&json_registry.x)
|
jbe@151
|
26 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
|
jbe@151
|
27 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
|
jbe@151
|
28 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
|
jbe@145
|
29
|
jbe@144
|
30 // generate dummy memory addresses that represent Lua objects
|
jbe@145
|
31 // via lightuserdata keys and LUA_REGISTRYINDEX:
|
jbe@144
|
32 static struct {
|
jbe@145
|
33 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
|
jbe@145
|
34 JSON_REGENT objectmt; // metatable for JSON objects
|
jbe@145
|
35 JSON_REGENT arraymt; // metatable for JSON arrays
|
jbe@144
|
36 } json_registry;
|
jbe@138
|
37
|
jbe@157
|
38 // returns the string "<JSON null marker>":
|
jbe@157
|
39 static int json_nullmark_tostring(lua_State *L) {
|
jbe@157
|
40 lua_pushliteral(L, "<JSON null marker>");
|
jbe@157
|
41 return 1;
|
jbe@157
|
42 }
|
jbe@157
|
43
|
jbe@169
|
44 #define json_convert_source_idx 1
|
jbe@169
|
45 #define json_convert_iterator_idx 2
|
jbe@169
|
46 #define json_convert_output_idx 3
|
jbe@169
|
47 #define json_convert_shadow_idx 4
|
jbe@169
|
48
|
jbe@169
|
49 // converts a Lua table to a JSON object or JSON array:
|
jbe@169
|
50 // (does never modify the argument, returns an empty object or array if argument is nil)
|
jbe@169
|
51 static int json_convert(lua_State *L, int array) {
|
jbe@169
|
52 lua_settop(L, 1);
|
jbe@169
|
53 if (lua_isnoneornil(L, json_convert_source_idx)) {
|
jbe@144
|
54 json_regfetch(L, shadowtbl);
|
jbe@169
|
55 lua_newtable(L);
|
jbe@169
|
56 lua_pushvalue(L, -1);
|
jbe@169
|
57 lua_newtable(L);
|
jbe@169
|
58 lua_rawset(L, -4);
|
jbe@169
|
59 } else {
|
jbe@169
|
60 // push iterator function on stack position 2 if existent,
|
jbe@169
|
61 // else push null for normal tables:
|
jbe@169
|
62 if (lua_getmetatable(L, json_convert_source_idx)) {
|
jbe@169
|
63 lua_getfield(L, -1, array ? "__ipairs" : "__pairs");
|
jbe@169
|
64 if (lua_isnil(L, -1)) luaL_checktype(L, 1, LUA_TTABLE);
|
jbe@169
|
65 else if (lua_type(L, -1) != LUA_TFUNCTION)
|
jbe@169
|
66 return luaL_error(L, "%s metamethod is not a function", array ? "__ipairs" : "__pairs");
|
jbe@169
|
67 lua_replace(L, -2);
|
jbe@169
|
68 } else {
|
jbe@169
|
69 lua_pushnil(L);
|
jbe@143
|
70 }
|
jbe@169
|
71 // create table on stack position 3:
|
jbe@169
|
72 lua_newtable(L);
|
jbe@169
|
73 // create shadow table on stack position 4:
|
jbe@169
|
74 json_regfetch(L, shadowtbl);
|
jbe@169
|
75 lua_newtable(L);
|
jbe@169
|
76 lua_pushvalue(L, json_convert_output_idx);
|
jbe@169
|
77 lua_pushvalue(L, -2);
|
jbe@169
|
78 lua_rawset(L, -4);
|
jbe@169
|
79 lua_replace(L, -2);
|
jbe@169
|
80 if (lua_isnil(L, json_convert_iterator_idx)) {
|
jbe@169
|
81 for (lua_pushnil(L); lua_next(L, json_convert_source_idx); lua_pop(L, 1)) {
|
jbe@169
|
82 lua_pushvalue(L, -2);
|
jbe@169
|
83 lua_pushvalue(L, -2);
|
jbe@169
|
84 lua_rawset(L, json_convert_shadow_idx);
|
jbe@169
|
85 }
|
jbe@169
|
86 } else {
|
jbe@169
|
87 return luaL_error(L, "Using %s metamethod not implemented yet", array ? "__ipairs" : "__pairs");
|
jbe@143
|
88 }
|
jbe@169
|
89 lua_settop(L, json_convert_output_idx);
|
jbe@136
|
90 }
|
jbe@136
|
91 // set metatable:
|
jbe@169
|
92 if (array) json_regfetch(L, arraymt);
|
jbe@169
|
93 else json_regfetch(L, objectmt);
|
jbe@169
|
94 lua_setmetatable(L, -2);
|
jbe@138
|
95 // return table:
|
jbe@136
|
96 return 1;
|
jbe@136
|
97 }
|
jbe@136
|
98
|
jbe@136
|
99 static int json_object(lua_State *L) {
|
jbe@169
|
100 return json_convert(L, 0);
|
jbe@136
|
101 }
|
jbe@136
|
102
|
jbe@136
|
103 static int json_array(lua_State *L) {
|
jbe@169
|
104 return json_convert(L, 1);
|
jbe@136
|
105 }
|
jbe@136
|
106
|
jbe@145
|
107 // internal states of JSON parser:
|
jbe@124
|
108 #define JSON_STATE_VALUE 0
|
jbe@124
|
109 #define JSON_STATE_OBJECT_KEY 1
|
jbe@124
|
110 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
|
jbe@124
|
111 #define JSON_STATE_OBJECT_VALUE 3
|
jbe@124
|
112 #define JSON_STATE_OBJECT_SEPARATOR 4
|
jbe@124
|
113 #define JSON_STATE_ARRAY_VALUE 5
|
jbe@124
|
114 #define JSON_STATE_ARRAY_SEPARATOR 6
|
jbe@124
|
115 #define JSON_STATE_END 7
|
jbe@121
|
116
|
jbe@145
|
117 // special Lua stack indicies for json_import function:
|
jbe@138
|
118 #define json_import_objectmt_idx 2
|
jbe@138
|
119 #define json_import_arraymt_idx 3
|
jbe@138
|
120 #define json_import_shadowtbl_idx 4
|
jbe@138
|
121
|
jbe@168
|
122 // macros for hex decoding:
|
jbe@168
|
123 #define json_utf16_surrogate(x) ((x) >= 0xD800 && (x) <= 0xDFFF)
|
jbe@168
|
124 #define json_utf16_lead(x) ((x) >= 0xD800 && (x) <= 0xDBFF)
|
jbe@168
|
125 #define json_utf16_tail(x) ((x) >= 0xDC00 && (x) <= 0xDFFF)
|
jbe@167
|
126 #define json_import_readhex(x) \
|
jbe@167
|
127 do { \
|
jbe@167
|
128 x = 0; \
|
jbe@167
|
129 for (i=0; i<4; i++) { \
|
jbe@167
|
130 x <<= 4; \
|
jbe@167
|
131 c = str[pos++]; \
|
jbe@167
|
132 if (c >= '0' && c <= '9') x += c - '0'; \
|
jbe@167
|
133 else if (c >= 'A' && c <= 'F') x += c - 'A' + 10; \
|
jbe@167
|
134 else if (c >= 'a' && c <= 'f') x += c - 'a' + 10; \
|
jbe@167
|
135 else if (c == 0) goto json_import_unexpected_eof; \
|
jbe@167
|
136 else goto json_import_unexpected_escape; \
|
jbe@167
|
137 } \
|
jbe@167
|
138 } while (0)
|
jbe@167
|
139
|
jbe@136
|
140 // decodes a JSON document:
|
jbe@121
|
141 static int json_import(lua_State *L) {
|
jbe@167
|
142 int i; // loop variable
|
jbe@136
|
143 const char *str; // string to parse
|
jbe@136
|
144 size_t total; // total length of string to parse
|
jbe@136
|
145 size_t pos = 0; // current position in string to parse
|
jbe@136
|
146 size_t level = 0; // nested levels of objects/arrays currently being processed
|
jbe@145
|
147 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
|
jbe@170
|
148 unsigned char c; // variable to store a single character to be processed (unsigned!)
|
jbe@145
|
149 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
|
jbe@145
|
150 char *cbuf; // C buffer to decode JSON string values
|
jbe@162
|
151 size_t outlen; // maximum length or write position of C buffer
|
jbe@167
|
152 long codepoint; // decoded UTF-16 character or higher codepoint
|
jbe@167
|
153 long utf16tail; // second decoded UTF-16 character (surrogate tail)
|
jbe@152
|
154 size_t arraylen; // variable to temporarily store the array length
|
jbe@166
|
155 // require string as argument and convert to C string with length information:
|
jbe@166
|
156 str = luaL_checklstring(L, 1, &total);
|
jbe@166
|
157 // if string contains a NULL byte, this is a syntax error
|
jbe@166
|
158 if (strlen(str) != total) goto json_import_syntax_error;
|
jbe@147
|
159 // stack shall contain one function argument:
|
jbe@138
|
160 lua_settop(L, 1);
|
jbe@147
|
161 // push objectmt onto stack position 2:
|
jbe@144
|
162 json_regfetch(L, objectmt);
|
jbe@147
|
163 // push arraymt onto stack position 3:
|
jbe@144
|
164 json_regfetch(L, arraymt);
|
jbe@147
|
165 // push shadowtbl onto stack position 4:
|
jbe@144
|
166 json_regfetch(L, shadowtbl);
|
jbe@136
|
167 // main loop of parser:
|
jbe@136
|
168 json_import_loop:
|
jbe@136
|
169 // skip whitespace and store next character in variable 'c':
|
jbe@146
|
170 while (c = str[pos],
|
jbe@146
|
171 c == ' ' ||
|
jbe@146
|
172 c == '\f' ||
|
jbe@146
|
173 c == '\n' ||
|
jbe@146
|
174 c == '\r' ||
|
jbe@146
|
175 c == '\t' ||
|
jbe@146
|
176 c == '\v'
|
jbe@146
|
177 ) pos++;
|
jbe@170
|
178 // NOTE: variable c needs to be unsigned in the following code
|
jbe@136
|
179 // switch statement to handle certain (single) characters:
|
jbe@121
|
180 switch (c) {
|
jbe@136
|
181 // handle end of JSON document:
|
jbe@121
|
182 case 0:
|
jbe@136
|
183 // if end of JSON document was expected, then return top element of stack as result:
|
jbe@124
|
184 if (mode == JSON_STATE_END) return 1;
|
jbe@136
|
185 // otherwise, the JSON document was malformed:
|
jbe@167
|
186 if (level == 0) {
|
jbe@167
|
187 lua_pushnil(L);
|
jbe@167
|
188 lua_pushliteral(L, "Empty string");
|
jbe@167
|
189 } else {
|
jbe@167
|
190 json_import_unexpected_eof:
|
jbe@167
|
191 lua_pushnil(L);
|
jbe@167
|
192 lua_pushliteral(L, "Unexpected end of JSON document");
|
jbe@167
|
193 }
|
jbe@121
|
194 return 2;
|
jbe@136
|
195 // new JSON object:
|
jbe@121
|
196 case '{':
|
jbe@136
|
197 // if a JSON object is not expected here, then return an error:
|
jbe@146
|
198 if (
|
jbe@146
|
199 mode != JSON_STATE_VALUE &&
|
jbe@146
|
200 mode != JSON_STATE_OBJECT_VALUE &&
|
jbe@146
|
201 mode != JSON_STATE_ARRAY_VALUE
|
jbe@146
|
202 ) goto json_import_syntax_error;
|
jbe@136
|
203 // create JSON object on stack:
|
jbe@136
|
204 lua_newtable(L);
|
jbe@136
|
205 // set metatable of JSON object:
|
jbe@138
|
206 lua_pushvalue(L, json_import_objectmt_idx);
|
jbe@125
|
207 lua_setmetatable(L, -2);
|
jbe@136
|
208 // create internal shadow table on stack:
|
jbe@136
|
209 lua_newtable(L);
|
jbe@146
|
210 // register internal shadow table:
|
jbe@123
|
211 lua_pushvalue(L, -2);
|
jbe@123
|
212 lua_pushvalue(L, -2);
|
jbe@138
|
213 lua_rawset(L, json_import_shadowtbl_idx);
|
jbe@146
|
214 // expect object key (or end of object) to follow:
|
jbe@136
|
215 mode = JSON_STATE_OBJECT_KEY;
|
jbe@146
|
216 // jump to common code for opening JSON object and JSON array:
|
jbe@142
|
217 goto json_import_open;
|
jbe@136
|
218 // new JSON array:
|
jbe@121
|
219 case '[':
|
jbe@136
|
220 // if a JSON array is not expected here, then return an error:
|
jbe@146
|
221 if (
|
jbe@146
|
222 mode != JSON_STATE_VALUE &&
|
jbe@146
|
223 mode != JSON_STATE_OBJECT_VALUE &&
|
jbe@146
|
224 mode != JSON_STATE_ARRAY_VALUE
|
jbe@146
|
225 ) goto json_import_syntax_error;
|
jbe@136
|
226 // create JSON array on stack:
|
jbe@136
|
227 lua_newtable(L);
|
jbe@136
|
228 // set metatable of JSON array:
|
jbe@138
|
229 lua_pushvalue(L, json_import_arraymt_idx);
|
jbe@125
|
230 lua_setmetatable(L, -2);
|
jbe@136
|
231 // create internal shadow table on stack:
|
jbe@136
|
232 lua_newtable(L);
|
jbe@146
|
233 // register internal shadow table:
|
jbe@123
|
234 lua_pushvalue(L, -2);
|
jbe@123
|
235 lua_pushvalue(L, -2);
|
jbe@138
|
236 lua_rawset(L, json_import_shadowtbl_idx);
|
jbe@140
|
237 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
|
jbe@140
|
238 lua_pushnil(L);
|
jbe@146
|
239 // expect array value (or end of array) to follow:
|
jbe@142
|
240 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@142
|
241 // continue with common code for opening JSON object and JSON array:
|
jbe@146
|
242 // common code for opening JSON object or JSON array:
|
jbe@142
|
243 json_import_open:
|
jbe@142
|
244 // limit nested levels:
|
jbe@142
|
245 if (level >= JSON_MAXDEPTH) {
|
jbe@142
|
246 lua_pushnil(L);
|
jbe@164
|
247 lua_pushfstring(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
|
jbe@142
|
248 return 2;
|
jbe@142
|
249 }
|
jbe@142
|
250 // additional buffer overflow protection:
|
jbe@142
|
251 if (!lua_checkstack(L, LUA_MINSTACK))
|
jbe@142
|
252 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
|
jbe@136
|
253 // increment level:
|
jbe@121
|
254 level++;
|
jbe@142
|
255 // consume input character:
|
jbe@142
|
256 pos++;
|
jbe@121
|
257 goto json_import_loop;
|
jbe@136
|
258 // end of JSON object:
|
jbe@121
|
259 case '}':
|
jbe@136
|
260 // if end of JSON object is not expected here, then return an error:
|
jbe@146
|
261 if (
|
jbe@146
|
262 mode != JSON_STATE_OBJECT_KEY &&
|
jbe@146
|
263 mode != JSON_STATE_OBJECT_SEPARATOR
|
jbe@146
|
264 ) goto json_import_syntax_error;
|
jbe@136
|
265 // jump to common code for end of JSON object and JSON array:
|
jbe@121
|
266 goto json_import_close;
|
jbe@136
|
267 // end of JSON array:
|
jbe@121
|
268 case ']':
|
jbe@136
|
269 // if end of JSON array is not expected here, then return an error:
|
jbe@146
|
270 if (
|
jbe@146
|
271 mode != JSON_STATE_ARRAY_VALUE &&
|
jbe@146
|
272 mode != JSON_STATE_ARRAY_SEPARATOR
|
jbe@146
|
273 ) goto json_import_syntax_error;
|
jbe@146
|
274 // pop nil key/magic (that was needed to keep stack balance):
|
jbe@140
|
275 lua_pop(L, 1);
|
jbe@136
|
276 // continue with common code for end of JSON object and JSON array:
|
jbe@136
|
277 // common code for end of JSON object or JSON array:
|
jbe@121
|
278 json_import_close:
|
jbe@136
|
279 // consume input character:
|
jbe@121
|
280 pos++;
|
jbe@136
|
281 // pop shadow table:
|
jbe@136
|
282 lua_pop(L, 1);
|
jbe@136
|
283 // check if nested:
|
jbe@121
|
284 if (--level) {
|
jbe@146
|
285 // if nested,
|
jbe@146
|
286 // check if outer(!) structure is an array or object:
|
jbe@140
|
287 if (lua_isnil(L, -2)) {
|
jbe@136
|
288 // select array value processing:
|
jbe@124
|
289 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@121
|
290 } else {
|
jbe@136
|
291 // select object value processing:
|
jbe@124
|
292 mode = JSON_STATE_OBJECT_VALUE;
|
jbe@121
|
293 }
|
jbe@136
|
294 // store value in outer structure:
|
jbe@121
|
295 goto json_import_process_value;
|
jbe@121
|
296 }
|
jbe@136
|
297 // if not nested, then expect end of JSON document and continue with loop:
|
jbe@136
|
298 mode = JSON_STATE_END;
|
jbe@121
|
299 goto json_import_loop;
|
jbe@136
|
300 // key terminator:
|
jbe@121
|
301 case ':':
|
jbe@136
|
302 // if key terminator is not expected here, then return an error:
|
jbe@124
|
303 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
|
jbe@121
|
304 goto json_import_syntax_error;
|
jbe@136
|
305 // consume input character:
|
jbe@121
|
306 pos++;
|
jbe@146
|
307 // expect object value to follow:
|
jbe@124
|
308 mode = JSON_STATE_OBJECT_VALUE;
|
jbe@146
|
309 // continue with loop:
|
jbe@121
|
310 goto json_import_loop;
|
jbe@136
|
311 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
|
jbe@121
|
312 case ',':
|
jbe@146
|
313 // branch according to parser state:
|
jbe@124
|
314 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
|
jbe@146
|
315 // expect an object key to follow:
|
jbe@124
|
316 mode = JSON_STATE_OBJECT_KEY;
|
jbe@124
|
317 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
|
jbe@146
|
318 // expect an array value to follow:
|
jbe@124
|
319 mode = JSON_STATE_ARRAY_VALUE;
|
jbe@121
|
320 } else {
|
jbe@136
|
321 // if value terminator is not expected here, then return an error:
|
jbe@136
|
322 goto json_import_syntax_error;
|
jbe@121
|
323 }
|
jbe@136
|
324 // consume input character:
|
jbe@121
|
325 pos++;
|
jbe@136
|
326 // continue with loop:
|
jbe@121
|
327 goto json_import_loop;
|
jbe@136
|
328 // string literal:
|
jbe@121
|
329 case '"':
|
jbe@146
|
330 // consume quote character:
|
jbe@146
|
331 pos++;
|
jbe@162
|
332 // find last character in input string:
|
jbe@162
|
333 outlen = pos;
|
jbe@162
|
334 while ((c = str[outlen]) != '"') {
|
jbe@161
|
335 // consume one character:
|
jbe@162
|
336 outlen++;
|
jbe@161
|
337 // handle unexpected end of JSON document:
|
jbe@161
|
338 if (c == 0) goto json_import_unexpected_eof;
|
jbe@161
|
339 // consume one extra character when encountering an escaped quote:
|
jbe@162
|
340 else if (c == '\\' && str[outlen] == '"') outlen++;
|
jbe@161
|
341 }
|
jbe@162
|
342 // determine buffer length:
|
jbe@162
|
343 outlen -= pos;
|
jbe@161
|
344 // check if string is non empty:
|
jbe@162
|
345 if (outlen) {
|
jbe@161
|
346 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
|
jbe@162
|
347 cbuf = luaL_buffinitsize(L, &luabuf, outlen);
|
jbe@162
|
348 outlen = 0;
|
jbe@161
|
349 // loop through the characters until encountering end quote:
|
jbe@161
|
350 while ((c = str[pos++]) != '"') {
|
jbe@162
|
351 // NOTE: unexpected end cannot happen anymore
|
jbe@162
|
352 if (c < 32 || c == 127) {
|
jbe@161
|
353 // do not allow ASCII control characters:
|
jbe@161
|
354 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
|
jbe@161
|
355 // by this parser to allow different encodings than Unicode
|
jbe@161
|
356 lua_pushnil(L);
|
jbe@161
|
357 lua_pushliteral(L, "Unexpected control character in JSON string");
|
jbe@161
|
358 return 2;
|
jbe@161
|
359 } else if (c == '\\') {
|
jbe@161
|
360 // read next char after backslash escape:
|
jbe@161
|
361 c = str[pos++];
|
jbe@161
|
362 switch (c) {
|
jbe@161
|
363 // unexpected end-of-string:
|
jbe@161
|
364 case 0:
|
jbe@161
|
365 goto json_import_unexpected_eof;
|
jbe@161
|
366 // unescaping of quotation mark, slash, and backslash:
|
jbe@161
|
367 case '"':
|
jbe@161
|
368 case '/':
|
jbe@161
|
369 case '\\':
|
jbe@162
|
370 cbuf[outlen++] = c;
|
jbe@161
|
371 break;
|
jbe@161
|
372 // unescaping of backspace:
|
jbe@162
|
373 case 'b': cbuf[outlen++] = '\b'; break;
|
jbe@161
|
374 // unescaping of form-feed:
|
jbe@162
|
375 case 'f': cbuf[outlen++] = '\f'; break;
|
jbe@161
|
376 // unescaping of new-line:
|
jbe@162
|
377 case 'n': cbuf[outlen++] = '\n'; break;
|
jbe@161
|
378 // unescaping of carriage-return:
|
jbe@162
|
379 case 'r': cbuf[outlen++] = '\r'; break;
|
jbe@161
|
380 // unescaping of tabulator:
|
jbe@162
|
381 case 't': cbuf[outlen++] = '\t'; break;
|
jbe@161
|
382 // unescaping of UTF-16 characters
|
jbe@161
|
383 case 'u':
|
jbe@167
|
384 // decode 4 hex nibbles:
|
jbe@167
|
385 json_import_readhex(codepoint);
|
jbe@167
|
386 // handle surrogate character:
|
jbe@167
|
387 if (json_utf16_surrogate(codepoint)) {
|
jbe@167
|
388 // check if first surrogate is in valid range:
|
jbe@167
|
389 if (json_utf16_lead(codepoint)) {
|
jbe@167
|
390 // require second surrogate:
|
jbe@167
|
391 if ((c = str[pos++]) != '\\' || (c = str[pos++]) != 'u') {
|
jbe@167
|
392 if (c == 0) goto json_import_unexpected_eof;
|
jbe@167
|
393 else goto json_import_wrong_surrogate;
|
jbe@167
|
394 }
|
jbe@167
|
395 // read 4 hex nibbles of second surrogate character:
|
jbe@167
|
396 json_import_readhex(utf16tail);
|
jbe@167
|
397 // check if second surrogate is in valid range:
|
jbe@167
|
398 if (!json_utf16_tail(utf16tail)) goto json_import_wrong_surrogate;
|
jbe@167
|
399 // calculate codepoint:
|
jbe@167
|
400 codepoint = 0x10000 + (utf16tail - 0xDC00) + (codepoint - 0xD800) * 0x400;
|
jbe@167
|
401 } else {
|
jbe@167
|
402 // throw error for wrong surrogates:
|
jbe@167
|
403 json_import_wrong_surrogate:
|
jbe@167
|
404 lua_pushnil(L);
|
jbe@167
|
405 lua_pushliteral(L, "Illegal UTF-16 surrogate in JSON string escape sequence");
|
jbe@167
|
406 return 2;
|
jbe@167
|
407 }
|
jbe@167
|
408 }
|
jbe@167
|
409 // encode as UTF-8:
|
jbe@167
|
410 if (codepoint < 0x80) {
|
jbe@167
|
411 cbuf[outlen++] = (char)codepoint;
|
jbe@167
|
412 } else if (codepoint < 0x800) {
|
jbe@167
|
413 cbuf[outlen++] = (char)(0xc0 | (codepoint >> 6));
|
jbe@167
|
414 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
415 } else if (codepoint < 0x10000) {
|
jbe@167
|
416 cbuf[outlen++] = (char)(0xe0 | (codepoint >> 12));
|
jbe@167
|
417 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
|
jbe@167
|
418 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
419 } else {
|
jbe@167
|
420 cbuf[outlen++] = (char)(0xf0 | (codepoint >> 18));
|
jbe@167
|
421 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
|
jbe@167
|
422 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
|
jbe@167
|
423 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
|
jbe@167
|
424 }
|
jbe@167
|
425 break;
|
jbe@161
|
426 // unexpected escape sequence:
|
jbe@161
|
427 default:
|
jbe@167
|
428 json_import_unexpected_escape:
|
jbe@161
|
429 lua_pushnil(L);
|
jbe@161
|
430 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
|
jbe@161
|
431 return 2;
|
jbe@161
|
432 }
|
jbe@161
|
433 } else {
|
jbe@161
|
434 // normal character:
|
jbe@162
|
435 cbuf[outlen++] = c;
|
jbe@121
|
436 }
|
jbe@121
|
437 }
|
jbe@161
|
438 // process buffer to Lua string:
|
jbe@162
|
439 luaL_pushresultsize(&luabuf, outlen);
|
jbe@161
|
440 } else {
|
jbe@161
|
441 // if JSON string is empty,
|
jbe@161
|
442 // push empty Lua string:
|
jbe@161
|
443 lua_pushliteral(L, "");
|
jbe@167
|
444 // consume closing quote:
|
jbe@167
|
445 pos++;
|
jbe@121
|
446 }
|
jbe@136
|
447 // continue with processing of decoded string:
|
jbe@121
|
448 goto json_import_process_value;
|
jbe@121
|
449 }
|
jbe@136
|
450 // process values whose type is is not deducible from a single character:
|
jbe@136
|
451 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
|
jbe@146
|
452 // for numbers,
|
jbe@146
|
453 // use strtod() call to parse a (double precision) floating point number:
|
jbe@167
|
454 double numval;
|
jbe@122
|
455 char *endptr;
|
jbe@122
|
456 numval = strtod(str+pos, &endptr);
|
jbe@146
|
457 // catch parsing errors:
|
jbe@122
|
458 if (endptr == str+pos) goto json_import_syntax_error;
|
jbe@146
|
459 // consume characters that were parsed:
|
jbe@122
|
460 pos += endptr - (str+pos);
|
jbe@146
|
461 // push parsed (double precision) floating point number on Lua stack:
|
jbe@122
|
462 lua_pushnumber(L, numval);
|
jbe@122
|
463 } else if (!strncmp(str+pos, "true", 4)) {
|
jbe@136
|
464 // consume 4 input characters for "true":
|
jbe@121
|
465 pos += 4;
|
jbe@147
|
466 // put Lua true value onto stack:
|
jbe@136
|
467 lua_pushboolean(L, 1);
|
jbe@121
|
468 } else if (!strncmp(str+pos, "false", 5)) {
|
jbe@136
|
469 // consume 5 input characters for "false":
|
jbe@121
|
470 pos += 5;
|
jbe@147
|
471 // put Lua false value onto stack:
|
jbe@136
|
472 lua_pushboolean(L, 0);
|
jbe@121
|
473 } else if (!strncmp(str+pos, "null", 4)) {
|
jbe@136
|
474 // consume 4 input characters for "null":
|
jbe@136
|
475 pos += 4;
|
jbe@153
|
476 // different behavor for top-level and sub-levels:
|
jbe@153
|
477 if (level) {
|
jbe@153
|
478 // if sub-level,
|
jbe@153
|
479 // push special null-marker onto stack:
|
jbe@155
|
480 json_pushnullmark(L);
|
jbe@153
|
481 } else {
|
jbe@153
|
482 // if top-level,
|
jbe@153
|
483 // push nil onto stack:
|
jbe@153
|
484 lua_pushnil(L);
|
jbe@153
|
485 }
|
jbe@121
|
486 } else {
|
jbe@136
|
487 // all other cases are a syntax error:
|
jbe@121
|
488 goto json_import_syntax_error;
|
jbe@121
|
489 }
|
jbe@136
|
490 // process a decoded value or key value pair (expected on top of Lua stack):
|
jbe@136
|
491 json_import_process_value:
|
jbe@121
|
492 switch (mode) {
|
jbe@136
|
493 // an object key has been read:
|
jbe@124
|
494 case JSON_STATE_OBJECT_KEY:
|
jbe@136
|
495 // if an object key is not a string, then this is a syntax error:
|
jbe@121
|
496 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
|
jbe@146
|
497 // expect key terminator to follow:
|
jbe@124
|
498 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
|
jbe@146
|
499 // continue with loop:
|
jbe@121
|
500 goto json_import_loop;
|
jbe@136
|
501 // a key value pair has been read:
|
jbe@124
|
502 case JSON_STATE_OBJECT_VALUE:
|
jbe@136
|
503 // store key value pair in outer shadow table:
|
jbe@130
|
504 lua_rawset(L, -3);
|
jbe@146
|
505 // expect value terminator (or end of object) to follow:
|
jbe@124
|
506 mode = JSON_STATE_OBJECT_SEPARATOR;
|
jbe@146
|
507 // continue with loop:
|
jbe@121
|
508 goto json_import_loop;
|
jbe@136
|
509 // an array value has been read:
|
jbe@124
|
510 case JSON_STATE_ARRAY_VALUE:
|
jbe@152
|
511 // get current array length:
|
jbe@152
|
512 arraylen = lua_rawlen(L, -3);
|
jbe@152
|
513 // throw error if array would exceed INT_MAX elements:
|
jbe@152
|
514 // TODO: Lua 5.3 may support more elements
|
jbe@152
|
515 if (arraylen >= INT_MAX) {
|
jbe@152
|
516 lua_pushnil(L);
|
jbe@152
|
517 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
|
jbe@152
|
518 }
|
jbe@136
|
519 // store value in outer shadow table:
|
jbe@152
|
520 lua_rawseti(L, -3, arraylen + 1);
|
jbe@146
|
521 // expect value terminator (or end of object) to follow:
|
jbe@124
|
522 mode = JSON_STATE_ARRAY_SEPARATOR;
|
jbe@146
|
523 // continue with loop
|
jbe@121
|
524 goto json_import_loop;
|
jbe@136
|
525 // a single value has been read:
|
jbe@124
|
526 case JSON_STATE_VALUE:
|
jbe@136
|
527 // leave value on top of stack, expect end of JSON document, and continue with loop:
|
jbe@124
|
528 mode = JSON_STATE_END;
|
jbe@121
|
529 goto json_import_loop;
|
jbe@121
|
530 }
|
jbe@146
|
531 // syntax error handling (reachable by goto statement):
|
jbe@136
|
532 json_import_syntax_error:
|
jbe@121
|
533 lua_pushnil(L);
|
jbe@121
|
534 lua_pushliteral(L, "Syntax error in JSON document");
|
jbe@121
|
535 return 2;
|
jbe@121
|
536 }
|
jbe@121
|
537
|
jbe@146
|
538 // special Lua stack indicies for json_path function:
|
jbe@138
|
539 #define json_path_shadowtbl_idx 1
|
jbe@146
|
540
|
jbe@146
|
541 // stack offset of arguments to json_path function:
|
jbe@155
|
542 #define json_path_idxshift 1
|
jbe@138
|
543
|
jbe@146
|
544 // gets a value or its type from a JSON document (passed as first argument)
|
jbe@147
|
545 // using a path (passed as variable number of keys after first argument):
|
jbe@137
|
546 static int json_path(lua_State *L, int type_mode) {
|
jbe@146
|
547 int stacktop; // stack index of top of stack (after shifting)
|
jbe@146
|
548 int idx = 2 + json_path_idxshift; // stack index of current argument to process
|
jbe@148
|
549 // insert shadowtbl into stack at position 1 (shifting the arguments):
|
jbe@144
|
550 json_regfetch(L, shadowtbl);
|
jbe@138
|
551 lua_insert(L, 1);
|
jbe@146
|
552 // store stack index of top of stack:
|
jbe@138
|
553 stacktop = lua_gettop(L);
|
jbe@146
|
554 // use first argument as "current value" (stored on top of stack):
|
jbe@138
|
555 lua_pushvalue(L, 1 + json_path_idxshift);
|
jbe@146
|
556 // process each "path key" (2nd argument and following arguments):
|
jbe@138
|
557 while (idx <= stacktop) {
|
jbe@146
|
558 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
|
jbe@137
|
559 if (lua_isnil(L, -1)) return 1;
|
jbe@137
|
560 // try to get shadow table of "current value":
|
jbe@130
|
561 lua_pushvalue(L, -1);
|
jbe@138
|
562 lua_rawget(L, json_path_shadowtbl_idx);
|
jbe@126
|
563 if (lua_isnil(L, -1)) {
|
jbe@137
|
564 // if no shadow table is found,
|
jbe@130
|
565 if (lua_type(L, -1) == LUA_TTABLE) {
|
jbe@146
|
566 // and if "current value" is a table,
|
jbe@146
|
567 // drop nil from stack:
|
jbe@146
|
568 lua_pop(L, 1);
|
jbe@137
|
569 // get "next value" using the "path key":
|
jbe@130
|
570 lua_pushvalue(L, idx++);
|
jbe@130
|
571 lua_gettable(L, -2);
|
jbe@130
|
572 } else {
|
jbe@137
|
573 // if "current value" is not a table,
|
jbe@146
|
574 // then the path cannot be walked and nil (already on top of stack) is returned:
|
jbe@137
|
575 return 1;
|
jbe@130
|
576 }
|
jbe@130
|
577 } else {
|
jbe@137
|
578 // if a shadow table is found,
|
jbe@137
|
579 // set "current value" to its shadow table:
|
jbe@130
|
580 lua_replace(L, -2);
|
jbe@137
|
581 // get "next value" using the "path key":
|
jbe@130
|
582 lua_pushvalue(L, idx++);
|
jbe@130
|
583 lua_rawget(L, -2);
|
jbe@126
|
584 }
|
jbe@137
|
585 // the "next value" replaces the "current value":
|
jbe@130
|
586 lua_replace(L, -2);
|
jbe@126
|
587 }
|
jbe@137
|
588 if (!type_mode) {
|
jbe@137
|
589 // if a value (and not its type) was requested,
|
jbe@137
|
590 // check if value is the null-marker, and store nil on top of Lua stack in that case:
|
jbe@155
|
591 if (json_isnullmark(L, -1)) lua_pushnil(L);
|
jbe@137
|
592 } else {
|
jbe@137
|
593 // if the type was requested,
|
jbe@137
|
594 // check if value is the null-marker:
|
jbe@155
|
595 if (json_isnullmark(L, -1)) {
|
jbe@137
|
596 // if yes, store string "null" on top of Lua stack:
|
jbe@130
|
597 lua_pushliteral(L, "null");
|
jbe@137
|
598 } else {
|
jbe@137
|
599 // otherwise,
|
jbe@138
|
600 // check if metatable indicates "object" or "array":
|
jbe@138
|
601 if (lua_getmetatable(L, -1)) {
|
jbe@144
|
602 json_regfetch(L, objectmt);
|
jbe@138
|
603 if (lua_rawequal(L, -2, -1)) {
|
jbe@146
|
604 // if value has metatable for JSON objects,
|
jbe@138
|
605 // return string "object":
|
jbe@138
|
606 lua_pushliteral(L, "object");
|
jbe@138
|
607 return 1;
|
jbe@138
|
608 }
|
jbe@144
|
609 json_regfetch(L, arraymt);
|
jbe@138
|
610 if (lua_rawequal(L, -3, -1)) {
|
jbe@146
|
611 // if value has metatable for JSON arrays,
|
jbe@146
|
612 // return string "object":
|
jbe@138
|
613 lua_pushliteral(L, "array");
|
jbe@138
|
614 return 1;
|
jbe@138
|
615 }
|
jbe@146
|
616 // remove 3 metatables (one of the value, two for comparison) from stack:
|
jbe@138
|
617 lua_pop(L, 3);
|
jbe@138
|
618 }
|
jbe@138
|
619 // otherwise, get the Lua type:
|
jbe@138
|
620 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
|
jbe@126
|
621 }
|
jbe@126
|
622 }
|
jbe@137
|
623 // return the top most value on the Lua stack:
|
jbe@137
|
624 return 1;
|
jbe@130
|
625 }
|
jbe@130
|
626
|
jbe@147
|
627 // gets a value from a JSON document (passed as first argument)
|
jbe@147
|
628 // using a path (passed as variable number of keys after first argument):
|
jbe@130
|
629 static int json_get(lua_State *L) {
|
jbe@137
|
630 return json_path(L, 0);
|
jbe@130
|
631 }
|
jbe@130
|
632
|
jbe@147
|
633 // gets a value's type from a JSON document (passed as first argument)
|
jbe@147
|
634 // using a path (variable number of keys after first argument):
|
jbe@130
|
635 static int json_type(lua_State *L) {
|
jbe@137
|
636 return json_path(L, 1);
|
jbe@130
|
637 }
|
jbe@130
|
638
|
jbe@147
|
639 // returns the length of a JSON array (or zero for a table without numeric keys):
|
jbe@130
|
640 static int json_len(lua_State *L) {
|
jbe@147
|
641 // stack shall contain one function argument:
|
jbe@130
|
642 lua_settop(L, 1);
|
jbe@148
|
643 // try to get corresponding shadow table for first argument:
|
jbe@144
|
644 json_regfetch(L, shadowtbl);
|
jbe@130
|
645 lua_pushvalue(L, 1);
|
jbe@138
|
646 lua_rawget(L, -2);
|
jbe@147
|
647 // if shadow table does not exist, return length of argument, else length of shadow table:
|
jbe@147
|
648 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
|
jbe@123
|
649 return 1;
|
jbe@123
|
650 }
|
jbe@123
|
651
|
jbe@130
|
652 static int json_index(lua_State *L) {
|
jbe@148
|
653 // stack shall contain two function arguments:
|
jbe@130
|
654 lua_settop(L, 2);
|
jbe@155
|
655 // get corresponding shadow table for first argument:
|
jbe@144
|
656 json_regfetch(L, shadowtbl);
|
jbe@130
|
657 lua_pushvalue(L, 1);
|
jbe@155
|
658 lua_rawget(L, -2);
|
jbe@148
|
659 // throw error if no shadow table was found:
|
jbe@139
|
660 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@148
|
661 // use key passed as second argument to lookup value in shadow table:
|
jbe@130
|
662 lua_pushvalue(L, 2);
|
jbe@130
|
663 lua_rawget(L, -2);
|
jbe@148
|
664 // if value is null-marker, then push nil onto stack:
|
jbe@155
|
665 if (json_isnullmark(L, -1)) lua_pushnil(L);
|
jbe@148
|
666 // return either looked up value, or nil
|
jbe@127
|
667 return 1;
|
jbe@127
|
668 }
|
jbe@127
|
669
|
jbe@130
|
670 static int json_newindex(lua_State *L) {
|
jbe@148
|
671 // stack shall contain three function arguments:
|
jbe@130
|
672 lua_settop(L, 3);
|
jbe@148
|
673 // get corresponding shadow table for first argument:
|
jbe@144
|
674 json_regfetch(L, shadowtbl);
|
jbe@123
|
675 lua_pushvalue(L, 1);
|
jbe@143
|
676 lua_rawget(L, -2);
|
jbe@148
|
677 // throw error if no shadow table was found:
|
jbe@130
|
678 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@148
|
679 // replace first argument with shadow table:
|
jbe@130
|
680 lua_replace(L, 1);
|
jbe@148
|
681 // reset stack and use second and third argument to write to shadow table:
|
jbe@139
|
682 lua_settop(L, 3);
|
jbe@130
|
683 lua_rawset(L, 1);
|
jbe@148
|
684 // return nothing:
|
jbe@148
|
685 return 0;
|
jbe@121
|
686 }
|
jbe@121
|
687
|
jbe@135
|
688 static int json_pairs_iterfunc(lua_State *L) {
|
jbe@149
|
689 // stack shall contain two function arguments:
|
jbe@135
|
690 lua_settop(L, 2);
|
jbe@155
|
691 // get corresponding shadow table for first argument:
|
jbe@144
|
692 json_regfetch(L, shadowtbl);
|
jbe@135
|
693 lua_pushvalue(L, 1);
|
jbe@155
|
694 lua_rawget(L, -2);
|
jbe@149
|
695 // throw error if no shadow table was found:
|
jbe@135
|
696 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@149
|
697 // get next key value pair from shadow table (using previous key from argument 2)
|
jbe@149
|
698 // and return nothing if there is no next pair:
|
jbe@135
|
699 lua_pushvalue(L, 2);
|
jbe@135
|
700 if (!lua_next(L, -2)) return 0;
|
jbe@149
|
701 // replace null-marker with nil:
|
jbe@155
|
702 if (json_isnullmark(L, -1)) {
|
jbe@135
|
703 lua_pop(L, 1);
|
jbe@135
|
704 lua_pushnil(L);
|
jbe@135
|
705 }
|
jbe@149
|
706 // return key and value (or key and nil, if null-marker was found):
|
jbe@135
|
707 return 2;
|
jbe@135
|
708 }
|
jbe@135
|
709
|
jbe@149
|
710 // returns a triple such that 'for key, value in pairs(obj) do ... end'
|
jbe@149
|
711 // iterates through all key value pairs (including JSON null keys represented as Lua nil):
|
jbe@135
|
712 static int json_pairs(lua_State *L) {
|
jbe@149
|
713 // return triple of function json_pairs_iterfunc, first argument, and nil:
|
jbe@139
|
714 lua_pushcfunction(L, json_pairs_iterfunc);
|
jbe@135
|
715 lua_pushvalue(L, 1);
|
jbe@135
|
716 lua_pushnil(L);
|
jbe@135
|
717 return 3;
|
jbe@135
|
718 }
|
jbe@135
|
719
|
jbe@134
|
720 static int json_ipairs_iterfunc(lua_State *L) {
|
jbe@152
|
721 lua_Integer idx;
|
jbe@149
|
722 // stack shall contain two function arguments:
|
jbe@134
|
723 lua_settop(L, 2);
|
jbe@149
|
724 // calculate new index by incrementing second argument:
|
jbe@134
|
725 idx = lua_tointeger(L, 2) + 1;
|
jbe@149
|
726 // get corresponding shadow table for first argument:
|
jbe@155
|
727 json_regfetch(L, shadowtbl);
|
jbe@134
|
728 lua_pushvalue(L, 1);
|
jbe@155
|
729 lua_rawget(L, -2);
|
jbe@149
|
730 // throw error if no shadow table was found:
|
jbe@134
|
731 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
|
jbe@149
|
732 // do integer lookup in shadow table:
|
jbe@134
|
733 lua_rawgeti(L, -1, idx);
|
jbe@149
|
734 // return nothing if there was no value:
|
jbe@134
|
735 if (lua_isnil(L, -1)) return 0;
|
jbe@149
|
736 // return new index and
|
jbe@149
|
737 // either the looked up value if it is not equal to the null-marker
|
jbe@149
|
738 // or nil instead of null-marker:
|
jbe@134
|
739 lua_pushinteger(L, idx);
|
jbe@155
|
740 if (json_isnullmark(L, -2)) lua_pushnil(L);
|
jbe@134
|
741 else lua_pushvalue(L, -2);
|
jbe@134
|
742 return 2;
|
jbe@134
|
743 }
|
jbe@134
|
744
|
jbe@149
|
745 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
|
jbe@149
|
746 // iterates through all values (including JSON null represented as Lua nil):
|
jbe@134
|
747 static int json_ipairs(lua_State *L) {
|
jbe@149
|
748 // return triple of function json_ipairs_iterfunc, first argument, and zero:
|
jbe@139
|
749 lua_pushcfunction(L, json_ipairs_iterfunc);
|
jbe@134
|
750 lua_pushvalue(L, 1);
|
jbe@134
|
751 lua_pushinteger(L, 0);
|
jbe@134
|
752 return 3;
|
jbe@134
|
753 }
|
jbe@134
|
754
|
jbe@163
|
755 typedef struct {
|
jbe@163
|
756 size_t length;
|
jbe@163
|
757 const char *data;
|
jbe@163
|
758 } json_key_t;
|
jbe@163
|
759
|
jbe@163
|
760 static int json_key_cmp(json_key_t *key1, json_key_t *key2) {
|
jbe@163
|
761 size_t pos = 0;
|
jbe@163
|
762 unsigned char c1, c2;
|
jbe@163
|
763 while (1) {
|
jbe@163
|
764 if (key1->length > pos) {
|
jbe@163
|
765 if (key2->length > pos) {
|
jbe@163
|
766 c1 = key1->data[pos];
|
jbe@163
|
767 c2 = key2->data[pos];
|
jbe@163
|
768 if (c1 < c2) return -1;
|
jbe@163
|
769 else if (c1 > c2) return 1;
|
jbe@163
|
770 } else {
|
jbe@163
|
771 return 1;
|
jbe@163
|
772 }
|
jbe@163
|
773 } else {
|
jbe@163
|
774 if (key2->length > pos) {
|
jbe@163
|
775 return -1;
|
jbe@163
|
776 } else {
|
jbe@163
|
777 return 0;
|
jbe@163
|
778 }
|
jbe@163
|
779 }
|
jbe@163
|
780 pos++;
|
jbe@163
|
781 }
|
jbe@163
|
782 }
|
jbe@163
|
783
|
jbe@154
|
784 #define JSON_TABLETYPE_UNKNOWN 0
|
jbe@154
|
785 #define JSON_TABLETYPE_OBJECT 1
|
jbe@154
|
786 #define JSON_TABLETYPE_ARRAY 2
|
jbe@154
|
787
|
jbe@164
|
788 #define json_export_internal_indentstring_idx 1
|
jbe@164
|
789 #define json_export_internal_level_idx 2
|
jbe@164
|
790 #define json_export_internal_value_idx 3
|
jbe@164
|
791 #define json_export_internal_tmp_idx 4
|
jbe@164
|
792
|
jbe@164
|
793 static int json_export_internal(lua_State *L) {
|
jbe@164
|
794 int level;
|
jbe@164
|
795 int pretty;
|
jbe@164
|
796 int i;
|
jbe@154
|
797 lua_Number num;
|
jbe@154
|
798 const char *str;
|
jbe@154
|
799 unsigned char c;
|
jbe@154
|
800 size_t strlen;
|
jbe@154
|
801 size_t pos = 0;
|
jbe@154
|
802 luaL_Buffer buf;
|
jbe@154
|
803 char hexcode[7]; // backslash, character 'u', 4 hex digits, and terminating NULL byte
|
jbe@154
|
804 int tabletype = JSON_TABLETYPE_UNKNOWN;
|
jbe@164
|
805 int anyelement = 0;
|
jbe@163
|
806 size_t keycount = 0;
|
jbe@163
|
807 size_t keypos = 0;
|
jbe@165
|
808 json_key_t *keybuf = NULL;
|
jbe@154
|
809 lua_Integer idx;
|
jbe@164
|
810 lua_settop(L, json_export_internal_value_idx);
|
jbe@164
|
811 if (json_isnullmark(L, json_export_internal_value_idx)) {
|
jbe@164
|
812 lua_pop(L, 1);
|
jbe@157
|
813 lua_pushnil(L);
|
jbe@157
|
814 }
|
jbe@164
|
815 switch (lua_type(L, json_export_internal_value_idx)) {
|
jbe@154
|
816 case LUA_TNIL:
|
jbe@154
|
817 lua_pushliteral(L, "null");
|
jbe@154
|
818 return 1;
|
jbe@154
|
819 case LUA_TNUMBER:
|
jbe@164
|
820 num = lua_tonumber(L, json_export_internal_value_idx);
|
jbe@154
|
821 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
|
jbe@154
|
822 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
|
jbe@164
|
823 lua_tostring(L, json_export_internal_value_idx);
|
jbe@154
|
824 return 1;
|
jbe@154
|
825 case LUA_TBOOLEAN:
|
jbe@164
|
826 if (lua_toboolean(L, json_export_internal_value_idx)) {
|
jbe@164
|
827 lua_pushliteral(L, "true");
|
jbe@164
|
828 } else {
|
jbe@164
|
829 lua_pushliteral(L, "false");
|
jbe@164
|
830 }
|
jbe@154
|
831 return 1;
|
jbe@154
|
832 case LUA_TSTRING:
|
jbe@164
|
833 str = lua_tolstring(L, 3, &strlen);
|
jbe@154
|
834 luaL_buffinit(L, &buf);
|
jbe@154
|
835 luaL_addchar(&buf, '"');
|
jbe@154
|
836 while (pos < strlen) {
|
jbe@154
|
837 c = str[pos++];
|
jbe@154
|
838 if (c == '"') luaL_addstring(&buf, "\\\"");
|
jbe@154
|
839 else if (c == '\\') luaL_addstring(&buf, "\\\\");
|
jbe@154
|
840 else if (c == 127) luaL_addstring(&buf, "\\u007F");
|
jbe@154
|
841 else if (c >= 32) luaL_addchar(&buf, c);
|
jbe@154
|
842 else if (c == '\b') luaL_addstring(&buf, "\\b");
|
jbe@154
|
843 else if (c == '\f') luaL_addstring(&buf, "\\f");
|
jbe@154
|
844 else if (c == '\n') luaL_addstring(&buf, "\\n");
|
jbe@154
|
845 else if (c == '\r') luaL_addstring(&buf, "\\r");
|
jbe@154
|
846 else if (c == '\t') luaL_addstring(&buf, "\\t");
|
jbe@154
|
847 else if (c == '\v') luaL_addstring(&buf, "\\v");
|
jbe@154
|
848 else {
|
jbe@154
|
849 sprintf(hexcode, "\\u%04X", c);
|
jbe@154
|
850 luaL_addstring(&buf, hexcode);
|
jbe@154
|
851 }
|
jbe@154
|
852 }
|
jbe@154
|
853 luaL_addchar(&buf, '"');
|
jbe@154
|
854 luaL_pushresult(&buf);
|
jbe@154
|
855 return 1;
|
jbe@154
|
856 case LUA_TTABLE:
|
jbe@164
|
857 if (lua_getmetatable(L, json_export_internal_value_idx)) {
|
jbe@154
|
858 json_regfetch(L, objectmt);
|
jbe@154
|
859 if (lua_rawequal(L, -2, -1)) {
|
jbe@154
|
860 tabletype = JSON_TABLETYPE_OBJECT;
|
jbe@154
|
861 } else {
|
jbe@154
|
862 json_regfetch(L, arraymt);
|
jbe@164
|
863 if (lua_rawequal(L, -3, -1)) {
|
jbe@164
|
864 tabletype = JSON_TABLETYPE_ARRAY;
|
jbe@164
|
865 } else {
|
jbe@164
|
866 return luaL_error(L, "JSON export not possible for tables with nonsupported metatable");
|
jbe@164
|
867 }
|
jbe@154
|
868 }
|
jbe@154
|
869 }
|
jbe@154
|
870 json_regfetch(L, shadowtbl);
|
jbe@164
|
871 lua_pushvalue(L, json_export_internal_value_idx);
|
jbe@154
|
872 lua_rawget(L, -2);
|
jbe@164
|
873 if (!lua_isnil(L, -1)) lua_replace(L, json_export_internal_value_idx);
|
jbe@164
|
874 lua_settop(L, json_export_internal_value_idx);
|
jbe@154
|
875 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
|
jbe@164
|
876 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@164
|
877 switch (lua_type(L, -2)) {
|
jbe@164
|
878 case LUA_TSTRING:
|
jbe@164
|
879 keycount++;
|
jbe@164
|
880 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_OBJECT;
|
jbe@164
|
881 else if (tabletype == JSON_TABLETYPE_ARRAY) goto json_export_tabletype_error;
|
jbe@164
|
882 break;
|
jbe@164
|
883 case LUA_TNUMBER:
|
jbe@164
|
884 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_ARRAY;
|
jbe@164
|
885 else if (tabletype == JSON_TABLETYPE_OBJECT) goto json_export_tabletype_error;
|
jbe@164
|
886 break;
|
jbe@154
|
887 }
|
jbe@154
|
888 }
|
jbe@154
|
889 }
|
jbe@164
|
890 pretty = lua_toboolean(L, json_export_internal_indentstring_idx);
|
jbe@164
|
891 level = lua_tointeger(L, json_export_internal_level_idx) + 1;
|
jbe@164
|
892 if (level > JSON_MAXDEPTH) {
|
jbe@164
|
893 return luaL_error(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
|
jbe@164
|
894 }
|
jbe@154
|
895 switch (tabletype) {
|
jbe@154
|
896 case JSON_TABLETYPE_OBJECT:
|
jbe@164
|
897 if (!keycount) {
|
jbe@164
|
898 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@164
|
899 if (lua_type(L, -2) == LUA_TSTRING) keycount++;
|
jbe@164
|
900 }
|
jbe@163
|
901 }
|
jbe@163
|
902 if (keycount) {
|
jbe@163
|
903 keybuf = calloc(keycount, sizeof(json_key_t));
|
jbe@163
|
904 if (!keybuf) return luaL_error(L, "Memory allocation failed in JSON library");
|
jbe@164
|
905 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
|
jbe@163
|
906 if (lua_type(L, -2) == LUA_TSTRING) {
|
jbe@163
|
907 json_key_t *key = keybuf + (keypos++);
|
jbe@163
|
908 key->data = lua_tolstring(L, -2, &key->length);
|
jbe@163
|
909 }
|
jbe@163
|
910 }
|
jbe@163
|
911 qsort(keybuf, keycount, sizeof(json_key_t), (void *)json_key_cmp);
|
jbe@163
|
912 }
|
jbe@154
|
913 luaL_buffinit(L, &buf);
|
jbe@154
|
914 luaL_addchar(&buf, '{');
|
jbe@163
|
915 for (keypos=0; keypos<keycount; keypos++) {
|
jbe@163
|
916 json_key_t *key = keybuf + keypos;
|
jbe@163
|
917 if (keypos) luaL_addchar(&buf, ',');
|
jbe@164
|
918 if (pretty) {
|
jbe@164
|
919 luaL_addchar(&buf, '\n');
|
jbe@164
|
920 for (i=0; i<level; i++) {
|
jbe@164
|
921 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
922 luaL_addvalue(&buf);
|
jbe@164
|
923 }
|
jbe@164
|
924 }
|
jbe@164
|
925 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
926 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
927 lua_pushinteger(L, level);
|
jbe@163
|
928 lua_pushlstring(L, key->data, key->length);
|
jbe@164
|
929 if (lua_pcall(L, 3, 1, 0)) {
|
jbe@163
|
930 if (keybuf) free(keybuf);
|
jbe@163
|
931 return lua_error(L);
|
jbe@154
|
932 }
|
jbe@163
|
933 luaL_addvalue(&buf);
|
jbe@163
|
934 luaL_addchar(&buf, ':');
|
jbe@164
|
935 if (pretty) luaL_addchar(&buf, ' ');
|
jbe@164
|
936 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
937 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
938 lua_pushinteger(L, level);
|
jbe@163
|
939 lua_pushlstring(L, key->data, key->length);
|
jbe@164
|
940 lua_rawget(L, json_export_internal_value_idx);
|
jbe@164
|
941 if (lua_pcall(L, 3, 1, 0)) {
|
jbe@163
|
942 if (keybuf) free(keybuf);
|
jbe@163
|
943 return lua_error(L);
|
jbe@163
|
944 }
|
jbe@163
|
945 luaL_addvalue(&buf);
|
jbe@154
|
946 }
|
jbe@163
|
947 if (keybuf) free(keybuf);
|
jbe@164
|
948 if (pretty && keycount != 0) {
|
jbe@164
|
949 luaL_addchar(&buf, '\n');
|
jbe@164
|
950 for (i=0; i<level-1; i++) {
|
jbe@164
|
951 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
952 luaL_addvalue(&buf);
|
jbe@164
|
953 }
|
jbe@164
|
954 }
|
jbe@154
|
955 luaL_addchar(&buf, '}');
|
jbe@164
|
956 if (pretty && level == 1) luaL_addchar(&buf, '\n');
|
jbe@154
|
957 luaL_pushresult(&buf);
|
jbe@154
|
958 return 1;
|
jbe@154
|
959 case JSON_TABLETYPE_ARRAY:
|
jbe@164
|
960 lua_settop(L, json_export_internal_tmp_idx);
|
jbe@154
|
961 luaL_buffinit(L, &buf);
|
jbe@154
|
962 luaL_addchar(&buf, '[');
|
jbe@154
|
963 for (idx = 1; ; idx++) {
|
jbe@164
|
964 lua_rawgeti(L, json_export_internal_value_idx, idx);
|
jbe@154
|
965 if (lua_isnil(L, -1)) {
|
jbe@154
|
966 lua_pop(L, 1);
|
jbe@154
|
967 break;
|
jbe@154
|
968 }
|
jbe@164
|
969 lua_replace(L, json_export_internal_tmp_idx);
|
jbe@164
|
970 if (anyelement) luaL_addchar(&buf, ',');
|
jbe@164
|
971 anyelement = 1;
|
jbe@164
|
972 if (pretty) {
|
jbe@164
|
973 luaL_addchar(&buf, '\n');
|
jbe@164
|
974 for (i=0; i<level; i++) {
|
jbe@164
|
975 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
976 luaL_addvalue(&buf);
|
jbe@164
|
977 }
|
jbe@164
|
978 }
|
jbe@164
|
979 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
980 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
981 lua_pushinteger(L, level);
|
jbe@164
|
982 lua_pushvalue(L, json_export_internal_tmp_idx);
|
jbe@164
|
983 lua_call(L, 3, 1);
|
jbe@154
|
984 luaL_addvalue(&buf);
|
jbe@154
|
985 }
|
jbe@164
|
986 if (pretty && anyelement) {
|
jbe@164
|
987 luaL_addchar(&buf, '\n');
|
jbe@164
|
988 for (i=0; i<level-1; i++) {
|
jbe@164
|
989 lua_pushvalue(L, json_export_internal_indentstring_idx);
|
jbe@164
|
990 luaL_addvalue(&buf);
|
jbe@164
|
991 }
|
jbe@164
|
992 }
|
jbe@154
|
993 luaL_addchar(&buf, ']');
|
jbe@164
|
994 if (pretty && level == 1) luaL_addchar(&buf, '\n');
|
jbe@154
|
995 luaL_pushresult(&buf);
|
jbe@154
|
996 return 1;
|
jbe@154
|
997 }
|
jbe@154
|
998 json_export_tabletype_error:
|
jbe@154
|
999 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
|
jbe@154
|
1000 }
|
jbe@166
|
1001 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, json_export_internal_value_idx)));
|
jbe@154
|
1002 }
|
jbe@154
|
1003
|
jbe@164
|
1004 static int json_export(lua_State *L) {
|
jbe@164
|
1005 lua_settop(L, 1);
|
jbe@164
|
1006 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
1007 lua_pushnil(L);
|
jbe@164
|
1008 lua_pushinteger(L, 0);
|
jbe@164
|
1009 lua_pushvalue(L, 1);
|
jbe@164
|
1010 lua_call(L, 3, 1);
|
jbe@164
|
1011 return 1;
|
jbe@164
|
1012 }
|
jbe@164
|
1013
|
jbe@164
|
1014 static int json_pretty(lua_State *L) {
|
jbe@164
|
1015 lua_settop(L, 2);
|
jbe@164
|
1016 lua_pushcfunction(L, json_export_internal);
|
jbe@164
|
1017 if (lua_isnil(L, 2)) lua_pushliteral(L, " ");
|
jbe@164
|
1018 else lua_pushvalue(L, 2);
|
jbe@164
|
1019 lua_pushinteger(L, 0);
|
jbe@164
|
1020 lua_pushvalue(L, 1);
|
jbe@164
|
1021 lua_call(L, 3, 1);
|
jbe@164
|
1022 return 1;
|
jbe@164
|
1023 }
|
jbe@164
|
1024
|
jbe@149
|
1025 // functions in library module:
|
jbe@121
|
1026 static const struct luaL_Reg json_module_functions[] = {
|
jbe@133
|
1027 {"object", json_object},
|
jbe@133
|
1028 {"array", json_array},
|
jbe@121
|
1029 {"import", json_import},
|
jbe@154
|
1030 {"export", json_export},
|
jbe@164
|
1031 {"pretty", json_pretty},
|
jbe@130
|
1032 {"get", json_get},
|
jbe@127
|
1033 {"type", json_type},
|
jbe@121
|
1034 {NULL, NULL}
|
jbe@121
|
1035 };
|
jbe@121
|
1036
|
jbe@149
|
1037 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
|
jbe@126
|
1038 static const struct luaL_Reg json_metatable_functions[] = {
|
jbe@130
|
1039 {"__len", json_len},
|
jbe@130
|
1040 {"__index", json_index},
|
jbe@130
|
1041 {"__newindex", json_newindex},
|
jbe@135
|
1042 {"__pairs", json_pairs},
|
jbe@134
|
1043 {"__ipairs", json_ipairs},
|
jbe@160
|
1044 {"__tostring", json_export},
|
jbe@126
|
1045 {NULL, NULL}
|
jbe@126
|
1046 };
|
jbe@126
|
1047
|
jbe@157
|
1048 // metamethods for JSON null marker:
|
jbe@157
|
1049 static const struct luaL_Reg json_nullmark_metamethods[] = {
|
jbe@157
|
1050 {"__tostring", json_nullmark_tostring},
|
jbe@157
|
1051 {NULL, NULL}
|
jbe@157
|
1052 };
|
jbe@157
|
1053
|
jbe@149
|
1054 // initializes json library:
|
jbe@121
|
1055 int luaopen_json(lua_State *L) {
|
jbe@149
|
1056 // empty stack:
|
jbe@126
|
1057 lua_settop(L, 0);
|
jbe@149
|
1058 // push library module onto stack position 1:
|
jbe@149
|
1059 lua_newtable(L);
|
jbe@149
|
1060 // register library functions:
|
jbe@149
|
1061 luaL_setfuncs(L, json_module_functions, 0);
|
jbe@149
|
1062 // create and store objectmt:
|
jbe@138
|
1063 lua_newtable(L);
|
jbe@138
|
1064 luaL_setfuncs(L, json_metatable_functions, 0);
|
jbe@144
|
1065 json_regstore(L, objectmt);
|
jbe@149
|
1066 // create and store arraymt:
|
jbe@138
|
1067 lua_newtable(L);
|
jbe@138
|
1068 luaL_setfuncs(L, json_metatable_functions, 0);
|
jbe@144
|
1069 json_regstore(L, arraymt);
|
jbe@149
|
1070 // create and store ephemeron table to store shadow tables for each JSON object/array
|
jbe@149
|
1071 // to allow NULL values returned as nil
|
jbe@149
|
1072 lua_newtable(L);
|
jbe@138
|
1073 lua_newtable(L); // metatable for ephemeron table
|
jbe@121
|
1074 lua_pushliteral(L, "__mode");
|
jbe@121
|
1075 lua_pushliteral(L, "k");
|
jbe@138
|
1076 lua_rawset(L, -3);
|
jbe@138
|
1077 lua_setmetatable(L, -2);
|
jbe@144
|
1078 json_regstore(L, shadowtbl);
|
jbe@157
|
1079 // set metatable of null marker and make it available through library module:
|
jbe@157
|
1080 json_pushnullmark(L);
|
jbe@157
|
1081 lua_newtable(L);
|
jbe@157
|
1082 luaL_setfuncs(L, json_nullmark_metamethods, 0);
|
jbe@157
|
1083 lua_setmetatable(L, -2);
|
jbe@157
|
1084 lua_setfield(L, 1, "null");
|
jbe@157
|
1085 // return library module (that's expected on top of stack):
|
jbe@121
|
1086 return 1;
|
jbe@121
|
1087 }
|