webmcp

view libraries/json/json.c @ 448:e3da778a8bf3

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

Impressum / About Us