webmcp

view libraries/json/json.c @ 179:461e5353ffb1

Limit max depth of JSON documents to 50 (until a better implementation of json.export is available)
author jbe
date Sat Aug 02 00:38:25 2014 +0200 (2014-08-02)
parents 20e393d2e6e1
children 887b77f71e5e
line source
1 #include <lua.h>
2 #include <lauxlib.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <math.h>
7 // maximum number of nested JSON values (objects and arrays):
8 // NOTE: The Lua reference states that the stack may typically contain at least
9 // "a few thousand elements". Since every nested level consumes
10 // 3 elements on the Lua stack (the object/array, its shadow table,
11 // a string key or a placeholder), we limit the number of nested levels
12 // to 500. If a stack overflow would still happen in the import function,
13 // this is detected nevertheless and an error is thrown (instead of
14 // returning nil and an error string).
15 #define JSON_MAXDEPTH 500
16 // NOTE: As long as the function json_export_internal is implemented
17 // recursively, JSON_MAXDEPTH needs to be low (e.g. 50) to avoid C stack
18 // overflows.
19 #if JSON_MAXDEPTH > 50
20 #define JSON_MAXDEPTH 50
21 #endif
23 // generate dummy memory addresses that represents null values:
24 char json_nullmark;
25 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
26 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
28 // macros for usage of Lua registry:
29 #define JSON_REGENT char
30 #define JSON_REGPOINTER void *
31 #define json_regpointer(x) (&json_registry.x)
32 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
33 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
34 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
36 // generate dummy memory addresses that represent Lua objects
37 // via lightuserdata keys and LUA_REGISTRYINDEX:
38 static struct {
39 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
40 JSON_REGENT objectmt; // metatable for JSON objects
41 JSON_REGENT arraymt; // metatable for JSON arrays
42 } json_registry;
44 // returns the string "<JSON null marker>":
45 static int json_nullmark_tostring(lua_State *L) {
46 lua_pushliteral(L, "<JSON null marker>");
47 return 1;
48 }
50 #define json_convert_source_idx 1
51 #define json_convert_iterator_idx 2
52 #define json_convert_output_idx 3
53 #define json_convert_shadow_idx 4
54 #define json_convert_iterfun_idx 5
55 #define json_convert_itertbl_idx 6
57 // converts a Lua table (or any other iterable value) to a JSON object or JSON array:
58 // (does never modify the argument, returns an empty object or array if argument is nil)
59 static int json_convert(lua_State *L, int array) {
60 int arrayidx = 0;
61 // determine is argument is given:
62 if (lua_isnoneornil(L, json_convert_source_idx)) {
63 // if no argument is given (or if argument is nil),
64 // create table with shadow table, and leave first table on top of stack:
65 json_regfetch(L, shadowtbl);
66 lua_newtable(L);
67 lua_pushvalue(L, -1);
68 lua_newtable(L);
69 lua_rawset(L, -4);
70 } else {
71 // if an argument was given,
72 // push its iterator function on stack position 2 if existent,
73 // else push null for normal tables:
74 lua_settop(L, 1);
75 if (lua_getmetatable(L, json_convert_source_idx)) {
76 lua_getfield(L, -1, array ? "__ipairs" : "__pairs");
77 if (lua_isnil(L, -1)) luaL_checktype(L, 1, LUA_TTABLE);
78 else if (lua_type(L, -1) != LUA_TFUNCTION)
79 return luaL_error(L, "%s metamethod is not a function", array ? "__ipairs" : "__pairs");
80 lua_replace(L, -2);
81 } else {
82 lua_pushnil(L);
83 }
84 // create result table on stack position 3:
85 lua_newtable(L);
86 // create shadow table on stack position 4:
87 json_regfetch(L, shadowtbl);
88 lua_newtable(L);
89 lua_pushvalue(L, json_convert_output_idx);
90 lua_pushvalue(L, -2);
91 lua_rawset(L, -4);
92 lua_replace(L, -2);
93 // check if iterator function exists:
94 if (lua_isnil(L, json_convert_iterator_idx)) {
95 // if there is no iterator function,
96 // distinguish between objects and arrays:
97 if (array == 0) {
98 // for an object, copy all string key value pairs to shadow table:
99 for (lua_pushnil(L); lua_next(L, json_convert_source_idx); lua_pop(L, 1)) {
100 if (lua_type(L, -2) == LUA_TSTRING) {
101 lua_pushvalue(L, -2);
102 lua_pushvalue(L, -2);
103 lua_rawset(L, json_convert_shadow_idx);
104 }
105 }
106 } else {
107 // for an array, copy consecutive integer value pairs to shadow table:
108 while (1) {
109 // throw error if array would exceed INT_MAX elements:
110 // TODO: Lua 5.3 may support more elements
111 if (arrayidx == INT_MAX) {
112 lua_pushnumber(L, (size_t)INT_MAX+1);
113 lua_rawget(L, json_convert_source_idx);
114 if (lua_isnil(L, -1)) break;
115 return luaL_error(L, "Array exceeded length of %d elements", INT_MAX);
116 }
117 // get next array entry:
118 arrayidx++;
119 lua_rawgeti(L, json_convert_source_idx, arrayidx);
120 // break if value is nil:
121 if (lua_isnil(L, -1)) break;
122 // store value in shadow table:
123 lua_rawseti(L, json_convert_shadow_idx, arrayidx);
124 }
125 }
126 } else {
127 // if there is an iterator function,
128 // call iterator function with source value (first argument)
129 // and store 3 result values on stack positions 5 through 7:
130 lua_pushvalue(L, json_convert_iterator_idx);
131 lua_pushvalue(L, 1);
132 lua_call(L, 1, 3);
133 // iterate through key value pairs and store some of them in shadow table
134 // while replacing nil values with null-marker:
135 while (1) {
136 // call iterfun function:
137 lua_pushvalue(L, json_convert_iterfun_idx);
138 lua_pushvalue(L, json_convert_itertbl_idx);
139 lua_pushvalue(L, -3);
140 lua_remove(L, -4);
141 lua_call(L, 2, 2);
142 // break iteration loop if key is nil:
143 if (lua_isnil(L, -2)) break;
144 // store key value pair only if key type is correct:
145 if (lua_type(L, -2) == (array ? LUA_TNUMBER : LUA_TSTRING)) {
146 // if key type is correct,
147 // push key onto stack:
148 lua_pushvalue(L, -2);
149 // if value is nil, push null-marker onto stack (as value):
150 if (lua_isnil(L, -2)) json_pushnullmark(L);
151 // else push value onto stack:
152 else lua_pushvalue(L, -2);
153 // set key value pair in shadow table:
154 lua_rawset(L, json_convert_shadow_idx);
155 }
156 // pop value from stack, but leave key on stack:
157 lua_pop(L, 1);
158 }
159 }
160 // let result table be on top of stack:
161 lua_settop(L, json_convert_output_idx);
162 }
163 // set metatable (for result table on top of stack):
164 if (array == 0) json_regfetch(L, objectmt);
165 else json_regfetch(L, arraymt);
166 lua_setmetatable(L, -2);
167 // return table on top of stack:
168 return 1;
169 }
171 // converts a Lua table (or any other iterable value) to a JSON object:
172 // (does never modify the argument, returns an empty object or array if argument is nil)
173 static int json_object(lua_State *L) {
174 return json_convert(L, 0);
175 }
177 // converts a Lua table (or any other iterable value) to a JSON array:
178 // (does never modify the argument, returns an empty object or array if argument is nil)
179 static int json_array(lua_State *L) {
180 return json_convert(L, 1);
181 }
183 // internal states of JSON parser:
184 #define JSON_STATE_VALUE 0
185 #define JSON_STATE_OBJECT_KEY 1
186 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
187 #define JSON_STATE_OBJECT_VALUE 3
188 #define JSON_STATE_OBJECT_SEPARATOR 4
189 #define JSON_STATE_ARRAY_VALUE 5
190 #define JSON_STATE_ARRAY_SEPARATOR 6
191 #define JSON_STATE_END 7
193 // special Lua stack indicies for json_import function:
194 #define json_import_objectmt_idx 2
195 #define json_import_arraymt_idx 3
196 #define json_import_shadowtbl_idx 4
198 // macros for hex decoding:
199 #define json_utf16_surrogate(x) ((x) >= 0xD800 && (x) <= 0xDFFF)
200 #define json_utf16_lead(x) ((x) >= 0xD800 && (x) <= 0xDBFF)
201 #define json_utf16_tail(x) ((x) >= 0xDC00 && (x) <= 0xDFFF)
202 #define json_import_readhex(x) \
203 do { \
204 x = 0; \
205 for (i=0; i<4; i++) { \
206 x <<= 4; \
207 c = str[pos++]; \
208 if (c >= '0' && c <= '9') x += c - '0'; \
209 else if (c >= 'A' && c <= 'F') x += c - 'A' + 10; \
210 else if (c >= 'a' && c <= 'f') x += c - 'a' + 10; \
211 else if (c == 0) goto json_import_unexpected_eof; \
212 else goto json_import_unexpected_escape; \
213 } \
214 } while (0)
216 // decodes a JSON document:
217 static int json_import(lua_State *L) {
218 int i; // loop variable
219 const char *str; // string to parse
220 size_t total; // total length of string to parse
221 size_t pos = 0; // current position in string to parse
222 size_t level = 0; // nested levels of objects/arrays currently being processed
223 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
224 unsigned char c; // variable to store a single character to be processed (unsigned!)
225 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
226 char *cbuf; // C buffer to decode JSON string values
227 size_t outlen; // maximum length or write position of C buffer
228 long codepoint; // decoded UTF-16 character or higher codepoint
229 long utf16tail; // second decoded UTF-16 character (surrogate tail)
230 size_t arraylen; // variable to temporarily store the array length
231 // require string as argument and convert to C string with length information:
232 str = luaL_checklstring(L, 1, &total);
233 // if string contains a NULL byte, this is a syntax error
234 if (strlen(str) != total) goto json_import_syntax_error;
235 // stack shall contain one function argument:
236 lua_settop(L, 1);
237 // push objectmt onto stack position 2:
238 json_regfetch(L, objectmt);
239 // push arraymt onto stack position 3:
240 json_regfetch(L, arraymt);
241 // push shadowtbl onto stack position 4:
242 json_regfetch(L, shadowtbl);
243 // main loop of parser:
244 json_import_loop:
245 // skip whitespace and store next character in variable 'c':
246 while (c = str[pos],
247 c == ' ' ||
248 c == '\f' ||
249 c == '\n' ||
250 c == '\r' ||
251 c == '\t' ||
252 c == '\v'
253 ) pos++;
254 // NOTE: variable c needs to be unsigned in the following code
255 // switch statement to handle certain (single) characters:
256 switch (c) {
257 // handle end of JSON document:
258 case 0:
259 // if end of JSON document was expected, then return top element of stack as result:
260 if (mode == JSON_STATE_END) return 1;
261 // otherwise, the JSON document was malformed:
262 if (level == 0) {
263 lua_pushnil(L);
264 lua_pushliteral(L, "Empty string");
265 } else {
266 json_import_unexpected_eof:
267 lua_pushnil(L);
268 lua_pushliteral(L, "Unexpected end of JSON document");
269 }
270 return 2;
271 // new JSON object:
272 case '{':
273 // if a JSON object is not expected here, then return an error:
274 if (
275 mode != JSON_STATE_VALUE &&
276 mode != JSON_STATE_OBJECT_VALUE &&
277 mode != JSON_STATE_ARRAY_VALUE
278 ) goto json_import_syntax_error;
279 // create JSON object on stack:
280 lua_newtable(L);
281 // set metatable of JSON object:
282 lua_pushvalue(L, json_import_objectmt_idx);
283 lua_setmetatable(L, -2);
284 // create internal shadow table on stack:
285 lua_newtable(L);
286 // register internal shadow table:
287 lua_pushvalue(L, -2);
288 lua_pushvalue(L, -2);
289 lua_rawset(L, json_import_shadowtbl_idx);
290 // expect object key (or end of object) to follow:
291 mode = JSON_STATE_OBJECT_KEY;
292 // jump to common code for opening JSON object and JSON array:
293 goto json_import_open;
294 // new JSON array:
295 case '[':
296 // if a JSON array is not expected here, then return an error:
297 if (
298 mode != JSON_STATE_VALUE &&
299 mode != JSON_STATE_OBJECT_VALUE &&
300 mode != JSON_STATE_ARRAY_VALUE
301 ) goto json_import_syntax_error;
302 // create JSON array on stack:
303 lua_newtable(L);
304 // set metatable of JSON array:
305 lua_pushvalue(L, json_import_arraymt_idx);
306 lua_setmetatable(L, -2);
307 // create internal shadow table on stack:
308 lua_newtable(L);
309 // register internal shadow table:
310 lua_pushvalue(L, -2);
311 lua_pushvalue(L, -2);
312 lua_rawset(L, json_import_shadowtbl_idx);
313 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
314 lua_pushnil(L);
315 // expect array value (or end of array) to follow:
316 mode = JSON_STATE_ARRAY_VALUE;
317 // continue with common code for opening JSON object and JSON array:
318 // common code for opening JSON object or JSON array:
319 json_import_open:
320 // limit nested levels:
321 if (level >= JSON_MAXDEPTH) {
322 lua_pushnil(L);
323 lua_pushfstring(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
324 return 2;
325 }
326 // additional buffer overflow protection:
327 if (!lua_checkstack(L, LUA_MINSTACK))
328 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
329 // increment level:
330 level++;
331 // consume input character:
332 pos++;
333 goto json_import_loop;
334 // end of JSON object:
335 case '}':
336 // if end of JSON object is not expected here, then return an error:
337 if (
338 mode != JSON_STATE_OBJECT_KEY &&
339 mode != JSON_STATE_OBJECT_SEPARATOR
340 ) goto json_import_syntax_error;
341 // jump to common code for end of JSON object and JSON array:
342 goto json_import_close;
343 // end of JSON array:
344 case ']':
345 // if end of JSON array is not expected here, then return an error:
346 if (
347 mode != JSON_STATE_ARRAY_VALUE &&
348 mode != JSON_STATE_ARRAY_SEPARATOR
349 ) goto json_import_syntax_error;
350 // pop nil key/magic (that was needed to keep stack balance):
351 lua_pop(L, 1);
352 // continue with common code for end of JSON object and JSON array:
353 // common code for end of JSON object or JSON array:
354 json_import_close:
355 // consume input character:
356 pos++;
357 // pop shadow table:
358 lua_pop(L, 1);
359 // check if nested:
360 if (--level) {
361 // if nested,
362 // check if outer(!) structure is an array or object:
363 if (lua_isnil(L, -2)) {
364 // select array value processing:
365 mode = JSON_STATE_ARRAY_VALUE;
366 } else {
367 // select object value processing:
368 mode = JSON_STATE_OBJECT_VALUE;
369 }
370 // store value in outer structure:
371 goto json_import_process_value;
372 }
373 // if not nested, then expect end of JSON document and continue with loop:
374 mode = JSON_STATE_END;
375 goto json_import_loop;
376 // key terminator:
377 case ':':
378 // if key terminator is not expected here, then return an error:
379 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
380 goto json_import_syntax_error;
381 // consume input character:
382 pos++;
383 // expect object value to follow:
384 mode = JSON_STATE_OBJECT_VALUE;
385 // continue with loop:
386 goto json_import_loop;
387 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
388 case ',':
389 // branch according to parser state:
390 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
391 // expect an object key to follow:
392 mode = JSON_STATE_OBJECT_KEY;
393 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
394 // expect an array value to follow:
395 mode = JSON_STATE_ARRAY_VALUE;
396 } else {
397 // if value terminator is not expected here, then return an error:
398 goto json_import_syntax_error;
399 }
400 // consume input character:
401 pos++;
402 // continue with loop:
403 goto json_import_loop;
404 // string literal:
405 case '"':
406 // consume quote character:
407 pos++;
408 // find last character in input string:
409 outlen = pos;
410 while ((c = str[outlen]) != '"') {
411 // consume one character:
412 outlen++;
413 // handle unexpected end of JSON document:
414 if (c == 0) goto json_import_unexpected_eof;
415 // consume one extra character when encountering an escaped quote:
416 else if (c == '\\' && str[outlen] == '"') outlen++;
417 }
418 // determine buffer length:
419 outlen -= pos;
420 // check if string is non empty:
421 if (outlen) {
422 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
423 cbuf = luaL_buffinitsize(L, &luabuf, outlen);
424 outlen = 0;
425 // loop through the characters until encountering end quote:
426 while ((c = str[pos++]) != '"') {
427 // NOTE: unexpected end cannot happen anymore
428 if (c < 32 || c == 127) {
429 // do not allow ASCII control characters:
430 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
431 // by this parser to allow different encodings than Unicode
432 lua_pushnil(L);
433 lua_pushliteral(L, "Unexpected control character in JSON string");
434 return 2;
435 } else if (c == '\\') {
436 // read next char after backslash escape:
437 c = str[pos++];
438 switch (c) {
439 // unexpected end-of-string:
440 case 0:
441 goto json_import_unexpected_eof;
442 // unescaping of quotation mark, slash, and backslash:
443 case '"':
444 case '/':
445 case '\\':
446 cbuf[outlen++] = c;
447 break;
448 // unescaping of backspace:
449 case 'b': cbuf[outlen++] = '\b'; break;
450 // unescaping of form-feed:
451 case 'f': cbuf[outlen++] = '\f'; break;
452 // unescaping of new-line:
453 case 'n': cbuf[outlen++] = '\n'; break;
454 // unescaping of carriage-return:
455 case 'r': cbuf[outlen++] = '\r'; break;
456 // unescaping of tabulator:
457 case 't': cbuf[outlen++] = '\t'; break;
458 // unescaping of UTF-16 characters
459 case 'u':
460 // decode 4 hex nibbles:
461 json_import_readhex(codepoint);
462 // handle surrogate character:
463 if (json_utf16_surrogate(codepoint)) {
464 // check if first surrogate is in valid range:
465 if (json_utf16_lead(codepoint)) {
466 // require second surrogate:
467 if ((c = str[pos++]) != '\\' || (c = str[pos++]) != 'u') {
468 if (c == 0) goto json_import_unexpected_eof;
469 else goto json_import_wrong_surrogate;
470 }
471 // read 4 hex nibbles of second surrogate character:
472 json_import_readhex(utf16tail);
473 // check if second surrogate is in valid range:
474 if (!json_utf16_tail(utf16tail)) goto json_import_wrong_surrogate;
475 // calculate codepoint:
476 codepoint = 0x10000 + (utf16tail - 0xDC00) + (codepoint - 0xD800) * 0x400;
477 } else {
478 // throw error for wrong surrogates:
479 json_import_wrong_surrogate:
480 lua_pushnil(L);
481 lua_pushliteral(L, "Illegal UTF-16 surrogate in JSON string escape sequence");
482 return 2;
483 }
484 }
485 // encode as UTF-8:
486 if (codepoint < 0x80) {
487 cbuf[outlen++] = (char)codepoint;
488 } else if (codepoint < 0x800) {
489 cbuf[outlen++] = (char)(0xc0 | (codepoint >> 6));
490 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
491 } else if (codepoint < 0x10000) {
492 cbuf[outlen++] = (char)(0xe0 | (codepoint >> 12));
493 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
494 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
495 } else {
496 cbuf[outlen++] = (char)(0xf0 | (codepoint >> 18));
497 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
498 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
499 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
500 }
501 break;
502 // unexpected escape sequence:
503 default:
504 json_import_unexpected_escape:
505 lua_pushnil(L);
506 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
507 return 2;
508 }
509 } else {
510 // normal character:
511 cbuf[outlen++] = c;
512 }
513 }
514 // process buffer to Lua string:
515 luaL_pushresultsize(&luabuf, outlen);
516 } else {
517 // if JSON string is empty,
518 // push empty Lua string:
519 lua_pushliteral(L, "");
520 // consume closing quote:
521 pos++;
522 }
523 // continue with processing of decoded string:
524 goto json_import_process_value;
525 }
526 // process values whose type is is not deducible from a single character:
527 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
528 // for numbers,
529 // use strtod() call to parse a (double precision) floating point number:
530 double numval;
531 char *endptr;
532 numval = strtod(str+pos, &endptr);
533 // catch parsing errors:
534 if (endptr == str+pos) goto json_import_syntax_error;
535 // consume characters that were parsed:
536 pos += endptr - (str+pos);
537 // push parsed (double precision) floating point number on Lua stack:
538 lua_pushnumber(L, numval);
539 } else if (!strncmp(str+pos, "true", 4)) {
540 // consume 4 input characters for "true":
541 pos += 4;
542 // put Lua true value onto stack:
543 lua_pushboolean(L, 1);
544 } else if (!strncmp(str+pos, "false", 5)) {
545 // consume 5 input characters for "false":
546 pos += 5;
547 // put Lua false value onto stack:
548 lua_pushboolean(L, 0);
549 } else if (!strncmp(str+pos, "null", 4)) {
550 // consume 4 input characters for "null":
551 pos += 4;
552 // different behavor for top-level and sub-levels:
553 if (level) {
554 // if sub-level,
555 // push special null-marker onto stack:
556 json_pushnullmark(L);
557 } else {
558 // if top-level,
559 // push nil onto stack:
560 lua_pushnil(L);
561 }
562 } else {
563 // all other cases are a syntax error:
564 goto json_import_syntax_error;
565 }
566 // process a decoded value or key value pair (expected on top of Lua stack):
567 json_import_process_value:
568 switch (mode) {
569 // an object key has been read:
570 case JSON_STATE_OBJECT_KEY:
571 // if an object key is not a string, then this is a syntax error:
572 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
573 // expect key terminator to follow:
574 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
575 // continue with loop:
576 goto json_import_loop;
577 // a key value pair has been read:
578 case JSON_STATE_OBJECT_VALUE:
579 // store key value pair in outer shadow table:
580 lua_rawset(L, -3);
581 // expect value terminator (or end of object) to follow:
582 mode = JSON_STATE_OBJECT_SEPARATOR;
583 // continue with loop:
584 goto json_import_loop;
585 // an array value has been read:
586 case JSON_STATE_ARRAY_VALUE:
587 // get current array length:
588 arraylen = lua_rawlen(L, -3);
589 // throw error if array would exceed INT_MAX elements:
590 // TODO: Lua 5.3 may support more elements
591 if (arraylen >= INT_MAX) {
592 lua_pushnil(L);
593 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
594 }
595 // store value in outer shadow table:
596 lua_rawseti(L, -3, arraylen + 1);
597 // expect value terminator (or end of object) to follow:
598 mode = JSON_STATE_ARRAY_SEPARATOR;
599 // continue with loop
600 goto json_import_loop;
601 // a single value has been read:
602 case JSON_STATE_VALUE:
603 // leave value on top of stack, expect end of JSON document, and continue with loop:
604 mode = JSON_STATE_END;
605 goto json_import_loop;
606 }
607 // syntax error handling (reachable by goto statement):
608 json_import_syntax_error:
609 lua_pushnil(L);
610 lua_pushliteral(L, "Syntax error in JSON document");
611 return 2;
612 }
614 // special Lua stack indicies for json_path function:
615 #define json_path_shadowtbl_idx 1
617 // stack offset of arguments to json_path function:
618 #define json_path_idxshift 1
620 // gets a value or its type from a JSON document (passed as first argument)
621 // using a path (passed as variable number of keys after the first argument):
622 static int json_path(lua_State *L, int type_mode) {
623 int stacktop; // stack index of top of stack (after shifting)
624 int idx = 2 + json_path_idxshift; // stack index of current argument to process
625 // require at least one argument:
626 luaL_checkany(L, 1);
627 // insert shadowtbl into stack at position 1 (shifting the arguments):
628 json_regfetch(L, shadowtbl);
629 lua_insert(L, 1);
630 // store stack index of top of stack:
631 stacktop = lua_gettop(L);
632 // use first argument as "current value" (stored on top of stack):
633 lua_pushvalue(L, 1 + json_path_idxshift);
634 // process each "path key" (2nd argument and following arguments):
635 while (idx <= stacktop) {
636 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
637 if (lua_isnil(L, -1)) return 1;
638 // try to get shadow table of "current value":
639 lua_pushvalue(L, -1);
640 lua_rawget(L, json_path_shadowtbl_idx);
641 if (lua_isnil(L, -1)) {
642 // if no shadow table is found,
643 if (lua_type(L, -1) == LUA_TTABLE) {
644 // and if "current value" is a table,
645 // drop nil from stack:
646 lua_pop(L, 1);
647 // get "next value" using the "path key":
648 lua_pushvalue(L, idx++);
649 lua_gettable(L, -2);
650 } else {
651 // if "current value" is not a table,
652 // then the path cannot be walked and nil (already on top of stack) is returned:
653 return 1;
654 }
655 } else {
656 // if a shadow table is found,
657 // set "current value" to its shadow table:
658 lua_replace(L, -2);
659 // get "next value" using the "path key":
660 lua_pushvalue(L, idx++);
661 lua_rawget(L, -2);
662 }
663 // the "next value" replaces the "current value":
664 lua_replace(L, -2);
665 }
666 if (!type_mode) {
667 // if a value (and not its type) was requested,
668 // check if value is the null-marker, and store nil on top of Lua stack in that case:
669 if (json_isnullmark(L, -1)) lua_pushnil(L);
670 } else {
671 // if the type was requested,
672 // check if value is the null-marker:
673 if (json_isnullmark(L, -1)) {
674 // if yes, store string "null" on top of Lua stack:
675 lua_pushliteral(L, "null");
676 } else {
677 // otherwise,
678 // check if metatable indicates "object" or "array":
679 if (lua_getmetatable(L, -1)) {
680 json_regfetch(L, objectmt);
681 if (lua_rawequal(L, -2, -1)) {
682 // if value has metatable for JSON objects,
683 // return string "object":
684 lua_pushliteral(L, "object");
685 return 1;
686 }
687 json_regfetch(L, arraymt);
688 if (lua_rawequal(L, -3, -1)) {
689 // if value has metatable for JSON arrays,
690 // return string "object":
691 lua_pushliteral(L, "array");
692 return 1;
693 }
694 // remove 3 metatables (one of the value, two for comparison) from stack:
695 lua_pop(L, 3);
696 }
697 // otherwise, get the Lua type:
698 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
699 }
700 }
701 // return the top most value on the Lua stack:
702 return 1;
703 }
705 // gets a value from a JSON document (passed as first argument)
706 // using a path (passed as variable number of keys after the first argument):
707 static int json_get(lua_State *L) {
708 return json_path(L, 0);
709 }
711 // gets a value's type from a JSON document (passed as first argument)
712 // using a path (passed as variable number of keys after first the argument):
713 static int json_type(lua_State *L) {
714 return json_path(L, 1);
715 }
717 // special Lua stack indicies for json_set function:
718 #define json_set_shadowtbl_idx 1
719 #define json_set_objectmt_idx 2
720 #define json_set_arraymt_idx 3
722 // stack offset of arguments to json_set function:
723 #define json_set_idxshift 3
725 // sets a value (passed as second argument) in a JSON document (passed as first argument)
726 // using a path (passed as variable number of keys starting at third argument):
727 static int json_set(lua_State *L) {
728 int stacktop; // stack index of top of stack (after shifting)
729 int idx = 3; // stack index of current argument to process
730 // require at least two arguments:
731 luaL_checkany(L, 1);
732 luaL_checkany(L, 2);
733 // insert shadowtbl into stack at position 1 (shifting the arguments):
734 json_regfetch(L, shadowtbl);
735 lua_insert(L, 1);
736 // insert objectmt into stack at position 2 (shifting the arguments):
737 json_regfetch(L, objectmt);
738 lua_insert(L, 2);
739 // insert arraymt into stack at position 3 (shifting the arguments):
740 json_regfetch(L, arraymt);
741 lua_insert(L, 3);
742 // store stack index of top of stack:
743 stacktop = lua_gettop(L);
744 // use nil as initial "parent value":
745 lua_pushnil(L);
746 // use first argument as "current value":
747 lua_pushvalue(L, 1 + json_set_idxshift);
748 // set all necessary values in path:
749 for (idx = 3 + json_set_idxshift; idx<=stacktop; idx++) {
750 // push metatable of "current value" onto stack:
751 if (!lua_getmetatable(L, -1)) lua_pushnil(L);
752 // distinguish according to type of path key:
753 switch (lua_type(L, idx)) {
754 case LUA_TSTRING:
755 // if path key is a string,
756 // check if "current value" is a JSON object (or table without metatable):
757 if (
758 lua_rawequal(L, -1, json_set_objectmt_idx) ||
759 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
760 ) {
761 // if "current value" is acceptable,
762 // pop metatable and leave "current value" on top of stack:
763 lua_pop(L, 1);
764 } else {
765 // if "current value" is not acceptable:
766 // pop metatable and "current value":
767 lua_pop(L, 2);
768 // throw error if parent element does not exist:
769 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON object");
770 // push new JSON object as "current value" onto stack:
771 lua_newtable(L);
772 // create and register shadow table:
773 lua_pushvalue(L, -1);
774 lua_newtable(L);
775 lua_rawset(L, json_set_shadowtbl_idx);
776 // set metatable of JSON object:
777 lua_pushvalue(L, json_set_objectmt_idx);
778 lua_setmetatable(L, -2);
779 // set entry in "parent value":
780 lua_pushvalue(L, idx-1);
781 lua_pushvalue(L, -2);
782 lua_settable(L, -4);
783 }
784 break;
785 case LUA_TNUMBER:
786 // if path key is a number,
787 // check if "current value" is a JSON array (or table without metatable):
788 if (
789 lua_rawequal(L, -1, json_set_arraymt_idx) ||
790 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
791 ) {
792 // if "current value" is acceptable,
793 // pop metatable and leave "current value" on top of stack:
794 lua_pop(L, 1);
795 } else {
796 // if "current value" is not acceptable:
797 // pop metatable and "current value":
798 lua_pop(L, 2);
799 // throw error if parent element does not exist:
800 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON array");
801 // push new JSON array as "current value" onto stack:
802 lua_newtable(L);
803 // create and register shadow table:
804 lua_pushvalue(L, -1);
805 lua_newtable(L);
806 lua_rawset(L, json_set_shadowtbl_idx);
807 // set metatable of JSON array:
808 lua_pushvalue(L, json_set_arraymt_idx);
809 lua_setmetatable(L, -2);
810 // set entry in "parent value":
811 lua_pushvalue(L, idx-1);
812 lua_pushvalue(L, -2);
813 lua_settable(L, -4);
814 }
815 break;
816 default:
817 return luaL_error(L, "Invalid path key of type %s", lua_typename(L, lua_type(L, idx)));
818 }
819 // check if last path element is being processed:
820 if (idx == stacktop) {
821 // if the last path element is being processed,
822 // set last path value in "current value" container:
823 lua_pushvalue(L, idx);
824 lua_pushvalue(L, 2 + json_set_idxshift);
825 lua_settable(L, -3);
826 } else {
827 // if the processed path element is not the last,
828 // use old "current value" as new "parent value"
829 lua_remove(L, -2);
830 // push new "current value" onto stack by performing a lookup:
831 lua_pushvalue(L, idx);
832 lua_gettable(L, -2);
833 }
834 }
835 // return first argument for convenience:
836 lua_settop(L, 1 + json_set_idxshift);
837 return 1;
838 }
840 // returns the length of a JSON array (or zero for a table without numeric keys):
841 static int json_len(lua_State *L) {
842 // stack shall contain one function argument:
843 lua_settop(L, 1);
844 // try to get corresponding shadow table for first argument:
845 json_regfetch(L, shadowtbl);
846 lua_pushvalue(L, 1);
847 lua_rawget(L, -2);
848 // if shadow table does not exist, return length of argument, else length of shadow table:
849 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
850 return 1;
851 }
853 // __index metamethod for JSON objects and JSON arrays:
854 static int json_index(lua_State *L) {
855 // stack shall contain two function arguments:
856 lua_settop(L, 2);
857 // get corresponding shadow table for first argument:
858 json_regfetch(L, shadowtbl);
859 lua_pushvalue(L, 1);
860 lua_rawget(L, -2);
861 // throw error if no shadow table was found:
862 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
863 // use key passed as second argument to lookup value in shadow table:
864 lua_pushvalue(L, 2);
865 lua_rawget(L, -2);
866 // if value is null-marker, then push nil onto stack:
867 if (json_isnullmark(L, -1)) lua_pushnil(L);
868 // return either looked up value, or nil
869 return 1;
870 }
872 // __newindex metamethod for JSON objects and JSON arrays:
873 static int json_newindex(lua_State *L) {
874 // stack shall contain three function arguments:
875 lua_settop(L, 3);
876 // get corresponding shadow table for first argument:
877 json_regfetch(L, shadowtbl);
878 lua_pushvalue(L, 1);
879 lua_rawget(L, -2);
880 // throw error if no shadow table was found:
881 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
882 // replace first argument with shadow table:
883 lua_replace(L, 1);
884 // reset stack and use second and third argument to write to shadow table:
885 lua_settop(L, 3);
886 lua_rawset(L, 1);
887 // return nothing:
888 return 0;
889 }
891 // function returned as first value by json_pairs function:
892 static int json_pairs_iterfunc(lua_State *L) {
893 // stack shall contain two function arguments:
894 lua_settop(L, 2);
895 // get corresponding shadow table for first argument:
896 json_regfetch(L, shadowtbl);
897 lua_pushvalue(L, 1);
898 lua_rawget(L, -2);
899 // throw error if no shadow table was found:
900 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
901 // get next key value pair from shadow table (using previous key from argument 2)
902 // and return nothing if there is no next pair:
903 lua_pushvalue(L, 2);
904 if (!lua_next(L, -2)) return 0;
905 // replace null-marker with nil:
906 if (json_isnullmark(L, -1)) {
907 lua_pop(L, 1);
908 lua_pushnil(L);
909 }
910 // return key and value (or key and nil, if null-marker was found):
911 return 2;
912 }
914 // returns a triple such that 'for key, value in pairs(obj) do ... end'
915 // iterates through all key value pairs (including JSON null values represented as Lua nil):
916 static int json_pairs(lua_State *L) {
917 // require one argument to function
918 luaL_checkany(L, 1);
919 // return triple of function json_pairs_iterfunc, first argument, and nil:
920 lua_pushcfunction(L, json_pairs_iterfunc);
921 lua_pushvalue(L, 1);
922 lua_pushnil(L);
923 return 3;
924 }
926 // function returned as first value by json_ipairs function:
927 static int json_ipairs_iterfunc(lua_State *L) {
928 lua_Integer idx;
929 // stack shall contain two function arguments:
930 lua_settop(L, 2);
931 // calculate new index by incrementing second argument:
932 idx = lua_tointeger(L, 2) + 1;
933 // get corresponding shadow table for first argument:
934 json_regfetch(L, shadowtbl);
935 lua_pushvalue(L, 1);
936 lua_rawget(L, -2);
937 // throw error if no shadow table was found:
938 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
939 // do integer lookup in shadow table:
940 lua_rawgeti(L, -1, idx);
941 // return nothing if there was no value:
942 if (lua_isnil(L, -1)) return 0;
943 // return new index and
944 // either the looked up value if it is not equal to the null-marker
945 // or nil instead of null-marker:
946 lua_pushinteger(L, idx);
947 if (json_isnullmark(L, -2)) lua_pushnil(L);
948 else lua_pushvalue(L, -2);
949 return 2;
950 }
952 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
953 // iterates through all values (including JSON null values represented as Lua nil):
954 static int json_ipairs(lua_State *L) {
955 // require one argument to function
956 luaL_checkany(L, 1);
957 // return triple of function json_ipairs_iterfunc, first argument, and zero:
958 lua_pushcfunction(L, json_ipairs_iterfunc);
959 lua_pushvalue(L, 1);
960 lua_pushinteger(L, 0);
961 return 3;
962 }
964 // datatype representing a table key:
965 // (used for sorting)
966 typedef struct {
967 size_t length;
968 const char *data;
969 } json_key_t;
971 // comparation function for table keys to be passed to qsort function:
972 static int json_key_cmp(json_key_t *key1, json_key_t *key2) {
973 size_t pos = 0;
974 unsigned char c1, c2;
975 while (1) {
976 if (key1->length > pos) {
977 if (key2->length > pos) {
978 c1 = key1->data[pos];
979 c2 = key2->data[pos];
980 if (c1 < c2) return -1;
981 else if (c1 > c2) return 1;
982 } else {
983 return 1;
984 }
985 } else {
986 if (key2->length > pos) {
987 return -1;
988 } else {
989 return 0;
990 }
991 }
992 pos++;
993 }
994 }
996 // constants for type detection of ambiguous tables:
997 #define JSON_TABLETYPE_UNKNOWN 0
998 #define JSON_TABLETYPE_OBJECT 1
999 #define JSON_TABLETYPE_ARRAY 2
1001 // special Lua stack indicies for json_export_internal function:
1002 #define json_export_internal_indentstring_idx 1
1003 #define json_export_internal_level_idx 2
1004 #define json_export_internal_value_idx 3
1005 #define json_export_internal_tmp_idx 4
1007 // encodes a JSON document (passed as third argument)
1008 // optionally using indentation (indentation string passed as first argument)
1009 // for a certain depth level (passed as second argument):
1010 static int json_export_internal(lua_State *L) {
1011 int level; // current depth level
1012 int pretty; // pretty printing on? (i.e. printing with indentation)
1013 int i; // iteration variable for level dependent repetitions:
1014 lua_Number num; // number to encode
1015 const char *str; // string to encode
1016 size_t strlen; // length of string to encode
1017 unsigned char c; // character to encode (unsigned!)
1018 size_t pos = 0; // position in string or position of current key (initialized with zero!)
1019 luaL_Buffer buf; // Lua buffer to create strings
1020 char hexcode[7]; // store for unicode hex escape sequence
1021 // NOTE: 7 bytes due to backslash, character 'u', 4 hex digits, and terminating NULL byte
1022 int tabletype = JSON_TABLETYPE_UNKNOWN; // table type: unknown, JSON object, or JSON array
1023 int anyelement = 0; // set to 1 if at least one array element has been processed
1024 size_t keycount = 0; // number of string keys in object
1025 json_key_t *keybuf = NULL; // temporary buffer to store (and sort) string keys of objects
1026 lua_Integer arrayidx; // index to iterate through arrays
1027 // stack shall contain three function arguments:
1028 lua_settop(L, json_export_internal_value_idx);
1029 // if value to encode is the null-marker, then treat it the same as nil:
1030 if (json_isnullmark(L, json_export_internal_value_idx)) {
1031 lua_pop(L, 1);
1032 lua_pushnil(L);
1034 // distinguish between different Lua types:
1035 switch (lua_type(L, json_export_internal_value_idx)) {
1036 // value to encode is nil:
1037 case LUA_TNIL:
1038 // return string "null":
1039 lua_pushliteral(L, "null");
1040 return 1;
1041 // value to encode is of type number:
1042 case LUA_TNUMBER:
1043 // convert value to double precision number:
1044 num = lua_tonumber(L, json_export_internal_value_idx);
1045 // throw error if number is not-a-number:
1046 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
1047 // throw error if number is positive or negative infinity:
1048 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
1049 // return Lua's string encoding of the number:
1050 lua_tostring(L, json_export_internal_value_idx);
1051 return 1;
1052 // value to encode is of type boolean:
1053 case LUA_TBOOLEAN:
1054 // return string "true" or "false" according to boolean value:
1055 if (lua_toboolean(L, json_export_internal_value_idx)) {
1056 lua_pushliteral(L, "true");
1057 } else {
1058 lua_pushliteral(L, "false");
1060 return 1;
1061 // value to encode is of type string:
1062 case LUA_TSTRING:
1063 // quote, escape and return string:
1064 str = lua_tolstring(L, 3, &strlen);
1065 luaL_buffinit(L, &buf);
1066 luaL_addchar(&buf, '"');
1067 while (pos < strlen) {
1068 c = str[pos++];
1069 if (c == '"') luaL_addstring(&buf, "\\\"");
1070 else if (c == '\\') luaL_addstring(&buf, "\\\\");
1071 else if (c == 127) luaL_addstring(&buf, "\\u007F");
1072 else if (c >= 32) luaL_addchar(&buf, c);
1073 else if (c == '\b') luaL_addstring(&buf, "\\b");
1074 else if (c == '\f') luaL_addstring(&buf, "\\f");
1075 else if (c == '\n') luaL_addstring(&buf, "\\n");
1076 else if (c == '\r') luaL_addstring(&buf, "\\r");
1077 else if (c == '\t') luaL_addstring(&buf, "\\t");
1078 else if (c == '\v') luaL_addstring(&buf, "\\v");
1079 else {
1080 sprintf(hexcode, "\\u%04X", c);
1081 luaL_addstring(&buf, hexcode);
1084 luaL_addchar(&buf, '"');
1085 luaL_pushresult(&buf);
1086 return 1;
1087 // value to encode is of type table (this includes JSON objects and JSON arrays):
1088 case LUA_TTABLE:
1089 // use table's metatable to try to determine type of table:
1090 if (lua_getmetatable(L, json_export_internal_value_idx)) {
1091 json_regfetch(L, objectmt);
1092 if (lua_rawequal(L, -2, -1)) {
1093 tabletype = JSON_TABLETYPE_OBJECT;
1094 } else {
1095 json_regfetch(L, arraymt);
1096 if (lua_rawequal(L, -3, -1)) {
1097 tabletype = JSON_TABLETYPE_ARRAY;
1098 } else {
1099 return luaL_error(L, "JSON export not possible for tables with nonsupported metatable");
1103 // replace table with its shadow table if existent, and reset stack:
1104 json_regfetch(L, shadowtbl);
1105 lua_pushvalue(L, json_export_internal_value_idx);
1106 lua_rawget(L, -2);
1107 if (!lua_isnil(L, -1)) lua_replace(L, json_export_internal_value_idx);
1108 lua_settop(L, json_export_internal_value_idx);
1109 // check if type of table is still undetermined:
1110 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
1111 // if yes, iterate over all keys:
1112 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1113 switch (lua_type(L, -2)) {
1114 case LUA_TSTRING:
1115 // for string keys,
1116 // increase keycount (may avoid another iteration):
1117 keycount++;
1118 // if type of table was unknown, then type of table is a JSON object now:
1119 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_OBJECT;
1120 // if type of table was a JSON array, then the type of table is ambiguous now
1121 // and an error is thrown:
1122 else if (tabletype == JSON_TABLETYPE_ARRAY) goto json_export_tabletype_error;
1123 break;
1124 case LUA_TNUMBER:
1125 // for numeric keys,
1126 // if type of table was unknown, then type of table is a JSON array now:
1127 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_ARRAY;
1128 // if type of table was a JSON object, then the type of table is ambiguous now
1129 // and an error is thrown:
1130 else if (tabletype == JSON_TABLETYPE_OBJECT) goto json_export_tabletype_error;
1131 break;
1135 // set pretty variable to 1 if pretty printing (with indentation) is desired:
1136 pretty = lua_toboolean(L, json_export_internal_indentstring_idx);
1137 // set level variable to corresponding function argument increased by one:
1138 level = lua_tointeger(L, json_export_internal_level_idx) + 1;
1139 // throw error if there are more levels that could be imported by this library:
1140 if (level > JSON_MAXDEPTH) {
1141 return luaL_error(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
1143 // distinguish between JSON objects and JSON arrays:
1144 switch (tabletype) {
1145 // JSON object:
1146 case JSON_TABLETYPE_OBJECT:
1147 // calculate count of string keys unless it has been calculated before:
1148 if (!keycount) {
1149 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1150 if (lua_type(L, -2) == LUA_TSTRING) keycount++;
1153 // create a sorted list of all string keys in memory:
1154 if (keycount) {
1155 // allocate memory for string keys:
1156 keybuf = calloc(keycount, sizeof(json_key_t));
1157 // check if memory allocation was successful:
1158 if (!keybuf) {
1159 // in case of memory exhaustion, try to collect garbage:
1160 lua_gc(L, LUA_GCCOLLECT, 0);
1161 // try to allocate memory again:
1162 keybuf = calloc(keycount, sizeof(json_key_t));
1163 // throw error if memory allocation failed again:
1164 if (!keybuf) {
1165 return luaL_error(L, "Memory allocation failed in JSON library");
1168 // copy all string keys to the C array:
1169 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
1170 if (lua_type(L, -2) == LUA_TSTRING) {
1171 json_key_t *key = keybuf + (pos++);
1172 key->data = lua_tolstring(L, -2, &key->length);
1175 // sort C array using quicksort:
1176 qsort(keybuf, keycount, sizeof(json_key_t), (void *)json_key_cmp);
1178 // create Lua string buffer:
1179 luaL_buffinit(L, &buf);
1180 // add opening bracket to output buffer:
1181 luaL_addchar(&buf, '{');
1182 // iterate through all (sorted) string keys:
1183 for (pos=0; pos<keycount; pos++) {
1184 json_key_t *key = keybuf + pos;
1185 // add comma to output buffer unless we process the first key:
1186 if (pos) luaL_addchar(&buf, ',');
1187 // handle indentation for pretty results:
1188 if (pretty) {
1189 luaL_addchar(&buf, '\n');
1190 for (i=0; i<level; i++) {
1191 lua_pushvalue(L, json_export_internal_indentstring_idx);
1192 luaL_addvalue(&buf);
1195 // recursive call to encode key:
1196 lua_pushcfunction(L, json_export_internal);
1197 lua_pushvalue(L, json_export_internal_indentstring_idx);
1198 lua_pushinteger(L, level);
1199 lua_pushlstring(L, key->data, key->length);
1200 if (lua_pcall(L, 3, 1, 0)) {
1201 // free memory of sorted string keys on error:
1202 if (keybuf) free(keybuf);
1203 // rethrow error:
1204 return lua_error(L);
1206 // add encoded key to output buffer:
1207 luaL_addvalue(&buf);
1208 // add colon to output buffer:
1209 luaL_addchar(&buf, ':');
1210 // handle indentation for pretty results:
1211 if (pretty) luaL_addchar(&buf, ' ');
1212 // recursive call to encode value:
1213 lua_pushcfunction(L, json_export_internal);
1214 lua_pushvalue(L, json_export_internal_indentstring_idx);
1215 lua_pushinteger(L, level);
1216 lua_pushlstring(L, key->data, key->length);
1217 lua_rawget(L, json_export_internal_value_idx);
1218 if (lua_pcall(L, 3, 1, 0)) {
1219 // free memory of sorted string keys on error:
1220 if (keybuf) free(keybuf);
1221 // rethrow error:
1222 return lua_error(L);
1224 // add encoded value to output buffer:
1225 luaL_addvalue(&buf);
1227 // decrement level variable for all following statements:
1228 level--;
1229 // free memory of sorted string keys:
1230 if (keybuf) free(keybuf);
1231 // handle indentation for pretty results:
1232 if (pretty && keycount != 0) {
1233 luaL_addchar(&buf, '\n');
1234 for (i=0; i<level; i++) {
1235 lua_pushvalue(L, json_export_internal_indentstring_idx);
1236 luaL_addvalue(&buf);
1239 // add closing bracket to output buffer:
1240 luaL_addchar(&buf, '}');
1241 // for pretty results, add final newline character if outermost container is processed:
1242 if (pretty && level == 0) luaL_addchar(&buf, '\n');
1243 // convert and return buffer:
1244 luaL_pushresult(&buf);
1245 return 1;
1246 // JSON array:
1247 case JSON_TABLETYPE_ARRAY:
1248 // reserve an extra element on the stack (needed because Lua buffer has unknown size on stack):
1249 lua_settop(L, json_export_internal_tmp_idx);
1250 // create Lua string buffer:
1251 luaL_buffinit(L, &buf);
1252 // add opening bracket to output buffer:
1253 luaL_addchar(&buf, '[');
1254 // iterate through integer keys:
1255 for (arrayidx = 1; ; arrayidx++) {
1256 // get value in array, and break if nil:
1257 lua_rawgeti(L, json_export_internal_value_idx, arrayidx);
1258 if (lua_isnil(L, -1)) {
1259 lua_pop(L, 1);
1260 break;
1262 // store value below Lua string buffer on stack (to allow operation on string buffer):
1263 lua_replace(L, json_export_internal_tmp_idx);
1264 //
1265 // add comma to output buffer unless we process the first element:
1266 if (anyelement) luaL_addchar(&buf, ',');
1267 // remember that we processed an element:
1268 anyelement = 1;
1269 // handle indentation for pretty results:
1270 if (pretty) {
1271 luaL_addchar(&buf, '\n');
1272 for (i=0; i<level; i++) {
1273 lua_pushvalue(L, json_export_internal_indentstring_idx);
1274 luaL_addvalue(&buf);
1277 // recursive call to encode previously stored value:
1278 lua_pushcfunction(L, json_export_internal);
1279 lua_pushvalue(L, json_export_internal_indentstring_idx);
1280 lua_pushinteger(L, level);
1281 lua_pushvalue(L, json_export_internal_tmp_idx);
1282 lua_call(L, 3, 1);
1283 // add encoded value to output buffer:
1284 luaL_addvalue(&buf);
1286 // decrement level variable for all following statements:
1287 level--;
1288 // handle indentation for pretty results:
1289 if (pretty && anyelement) {
1290 luaL_addchar(&buf, '\n');
1291 for (i=0; i<level; i++) {
1292 lua_pushvalue(L, json_export_internal_indentstring_idx);
1293 luaL_addvalue(&buf);
1296 // add closing bracket to output buffer:
1297 luaL_addchar(&buf, ']');
1298 // for pretty results, add final newline character if outermost container is processed:
1299 if (pretty && level == 0) luaL_addchar(&buf, '\n');
1300 // convert and return buffer:
1301 luaL_pushresult(&buf);
1302 return 1;
1304 // throw error if table type is unknown:
1305 json_export_tabletype_error:
1306 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
1308 // all other datatypes are considered an error:
1309 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, json_export_internal_value_idx)));
1312 // encodes a JSON document (passed as argument):
1313 static int json_export(lua_State *L) {
1314 // stack shall contain one function argument:
1315 lua_settop(L, 1);
1316 // call json_export_internal function with proper arguments:
1317 lua_pushcfunction(L, json_export_internal);
1318 lua_pushnil(L);
1319 lua_pushinteger(L, 0);
1320 lua_pushvalue(L, 1);
1321 lua_call(L, 3, 1);
1322 // return result:
1323 return 1;
1326 // encodes a JSON document (passed as first argument)
1327 // with indentation (indentation string may be passed as second argument):
1328 static int json_pretty(lua_State *L) {
1329 // stack shall contain two function arguments:
1330 lua_settop(L, 2);
1331 // call json_export_internal function with proper arguments:
1332 lua_pushcfunction(L, json_export_internal);
1333 if (lua_isnil(L, 2)) lua_pushliteral(L, " ");
1334 else lua_pushvalue(L, 2);
1335 lua_pushinteger(L, 0);
1336 lua_pushvalue(L, 1);
1337 lua_call(L, 3, 1);
1338 // return result:
1339 return 1;
1342 // functions in library module:
1343 static const struct luaL_Reg json_module_functions[] = {
1344 {"object", json_object},
1345 {"array", json_array},
1346 {"import", json_import},
1347 {"export", json_export},
1348 {"pretty", json_pretty},
1349 {"get", json_get},
1350 {"type", json_type},
1351 {"set", json_set},
1352 {NULL, NULL}
1353 };
1355 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
1356 static const struct luaL_Reg json_metatable_functions[] = {
1357 {"__len", json_len},
1358 {"__index", json_index},
1359 {"__newindex", json_newindex},
1360 {"__pairs", json_pairs},
1361 {"__ipairs", json_ipairs},
1362 {"__tostring", json_export},
1363 {NULL, NULL}
1364 };
1366 // metamethods for JSON null marker:
1367 static const struct luaL_Reg json_nullmark_metamethods[] = {
1368 {"__tostring", json_nullmark_tostring},
1369 {NULL, NULL}
1370 };
1372 // initializes json library:
1373 int luaopen_json(lua_State *L) {
1374 // empty stack:
1375 lua_settop(L, 0);
1376 // push library module onto stack position 1:
1377 lua_newtable(L);
1378 // register library functions:
1379 luaL_setfuncs(L, json_module_functions, 0);
1380 // create and store objectmt:
1381 lua_newtable(L);
1382 luaL_setfuncs(L, json_metatable_functions, 0);
1383 json_regstore(L, objectmt);
1384 // create and store arraymt:
1385 lua_newtable(L);
1386 luaL_setfuncs(L, json_metatable_functions, 0);
1387 json_regstore(L, arraymt);
1388 // create and store ephemeron table to store shadow tables for each JSON object/array
1389 // to allow NULL values returned as nil
1390 lua_newtable(L);
1391 lua_newtable(L); // metatable for ephemeron table
1392 lua_pushliteral(L, "__mode");
1393 lua_pushliteral(L, "k");
1394 lua_rawset(L, -3);
1395 lua_setmetatable(L, -2);
1396 json_regstore(L, shadowtbl);
1397 // set metatable of null marker and make it available through library module:
1398 json_pushnullmark(L);
1399 lua_newtable(L);
1400 luaL_setfuncs(L, json_nullmark_metamethods, 0);
1401 lua_setmetatable(L, -2);
1402 lua_setfield(L, 1, "null");
1403 // return library module (that's expected on top of stack):
1404 return 1;

Impressum / About Us