webmcp
view libraries/json/json.c @ 158:d42a7a840358
Removed function json.setnull(tbl, key) from JSON library
author | jbe |
---|---|
date | Thu Jul 31 03:49:43 2014 +0200 (2014-07-31) |
parents | 004d2d50419e |
children | ddb9b9b0d210 |
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
17 // generate dummy memory addresses that represents null values:
18 char json_nullmark;
19 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
20 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
22 // macros for usage of Lua registry:
23 #define JSON_REGENT char
24 #define JSON_REGPOINTER void *
25 #define json_regpointer(x) (&json_registry.x)
26 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
27 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
28 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
30 // generate dummy memory addresses that represent Lua objects
31 // via lightuserdata keys and LUA_REGISTRYINDEX:
32 static struct {
33 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
34 JSON_REGENT objectmt; // metatable for JSON objects
35 JSON_REGENT arraymt; // metatable for JSON arrays
36 } json_registry;
38 // returns the string "<JSON null marker>":
39 static int json_nullmark_tostring(lua_State *L) {
40 lua_pushliteral(L, "<JSON null marker>");
41 return 1;
42 }
44 // marks a Lua table as JSON object or JSON array:
45 // (returns its modified argument or a new table if argument is nil)
46 static int json_mark(lua_State *L, JSON_REGPOINTER mt) {
47 // check if argument is nil
48 if (lua_isnoneornil(L, 1)) {
49 // create new table at stack position 1:
50 lua_settop(L, 0);
51 lua_newtable(L);
52 // create shadow table (leaving previously created table on stack position 1):
53 json_regfetch(L, shadowtbl);
54 lua_pushvalue(L, 1);
55 lua_newtable(L);
56 lua_rawset(L, -3);
57 } else {
58 // push shadow table on top of stack:
59 json_regfetch(L, shadowtbl);
60 lua_pushvalue(L, 1);
61 lua_rawget(L, -2);
62 // if shadow table does not exist:
63 if (lua_isnil(L, -1)) {
64 // create shadow table and leave it on top of stack:
65 lua_newtable(L);
66 lua_pushvalue(L, 1);
67 lua_pushvalue(L, -2);
68 lua_rawset(L, -5);
69 }
70 // move elements from original table to shadow table (that's expected on top of stack):
71 for(lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
72 lua_pushvalue(L, -2);
73 lua_pushnil(L);
74 lua_rawset(L, 1);
75 lua_pushvalue(L, -2);
76 lua_pushvalue(L, -2);
77 lua_rawset(L, -5);
78 }
79 }
80 // discard everything but table to return:
81 lua_settop(L, 1);
82 // set metatable:
83 json_regfetchpointer(L, mt);
84 lua_setmetatable(L, 1);
85 // return table:
86 return 1;
87 }
89 // marks a table as JSON object:
90 // (returns its modified argument or a new table if argument is nil)
91 static int json_object(lua_State *L) {
92 return json_mark(L, json_regpointer(objectmt));
93 }
95 // marks a table as JSON array:
96 // (returns its modified argument or a new table if argument is nil)
97 static int json_array(lua_State *L) {
98 return json_mark(L, json_regpointer(arraymt));
99 }
101 // internal states of JSON parser:
102 #define JSON_STATE_VALUE 0
103 #define JSON_STATE_OBJECT_KEY 1
104 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
105 #define JSON_STATE_OBJECT_VALUE 3
106 #define JSON_STATE_OBJECT_SEPARATOR 4
107 #define JSON_STATE_ARRAY_VALUE 5
108 #define JSON_STATE_ARRAY_SEPARATOR 6
109 #define JSON_STATE_END 7
111 // special Lua stack indicies for json_import function:
112 #define json_import_objectmt_idx 2
113 #define json_import_arraymt_idx 3
114 #define json_import_shadowtbl_idx 4
116 // decodes a JSON document:
117 static int json_import(lua_State *L) {
118 const char *str; // string to parse
119 size_t total; // total length of string to parse
120 size_t pos = 0; // current position in string to parse
121 size_t level = 0; // nested levels of objects/arrays currently being processed
122 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
123 char c; // variable to store a single character to be processed
124 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
125 char *cbuf; // C buffer to decode JSON string values
126 size_t writepos; // write position of decoded strings in C buffer
127 size_t arraylen; // variable to temporarily store the array length
128 // stack shall contain one function argument:
129 lua_settop(L, 1);
130 // push objectmt onto stack position 2:
131 json_regfetch(L, objectmt);
132 // push arraymt onto stack position 3:
133 json_regfetch(L, arraymt);
134 // push shadowtbl onto stack position 4:
135 json_regfetch(L, shadowtbl);
136 // require string as first argument:
137 str = luaL_checklstring(L, 1, &total);
138 // if string contains a NULL byte, this is a syntax error
139 if (strlen(str) != total) goto json_import_syntax_error;
140 // main loop of parser:
141 json_import_loop:
142 // skip whitespace and store next character in variable 'c':
143 while (c = str[pos],
144 c == ' ' ||
145 c == '\f' ||
146 c == '\n' ||
147 c == '\r' ||
148 c == '\t' ||
149 c == '\v'
150 ) pos++;
151 // switch statement to handle certain (single) characters:
152 switch (c) {
153 // handle end of JSON document:
154 case 0:
155 // if end of JSON document was expected, then return top element of stack as result:
156 if (mode == JSON_STATE_END) return 1;
157 // otherwise, the JSON document was malformed:
158 json_import_unexpected_eof:
159 lua_pushnil(L);
160 if (level == 0) lua_pushliteral(L, "Empty string");
161 else lua_pushliteral(L, "Unexpected end of JSON document");
162 return 2;
163 // new JSON object:
164 case '{':
165 // if a JSON object is not expected here, then return an error:
166 if (
167 mode != JSON_STATE_VALUE &&
168 mode != JSON_STATE_OBJECT_VALUE &&
169 mode != JSON_STATE_ARRAY_VALUE
170 ) goto json_import_syntax_error;
171 // create JSON object on stack:
172 lua_newtable(L);
173 // set metatable of JSON object:
174 lua_pushvalue(L, json_import_objectmt_idx);
175 lua_setmetatable(L, -2);
176 // create internal shadow table on stack:
177 lua_newtable(L);
178 // register internal shadow table:
179 lua_pushvalue(L, -2);
180 lua_pushvalue(L, -2);
181 lua_rawset(L, json_import_shadowtbl_idx);
182 // expect object key (or end of object) to follow:
183 mode = JSON_STATE_OBJECT_KEY;
184 // jump to common code for opening JSON object and JSON array:
185 goto json_import_open;
186 // new JSON array:
187 case '[':
188 // if a JSON array is not expected here, then return an error:
189 if (
190 mode != JSON_STATE_VALUE &&
191 mode != JSON_STATE_OBJECT_VALUE &&
192 mode != JSON_STATE_ARRAY_VALUE
193 ) goto json_import_syntax_error;
194 // create JSON array on stack:
195 lua_newtable(L);
196 // set metatable of JSON array:
197 lua_pushvalue(L, json_import_arraymt_idx);
198 lua_setmetatable(L, -2);
199 // create internal shadow table on stack:
200 lua_newtable(L);
201 // register internal shadow table:
202 lua_pushvalue(L, -2);
203 lua_pushvalue(L, -2);
204 lua_rawset(L, json_import_shadowtbl_idx);
205 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
206 lua_pushnil(L);
207 // expect array value (or end of array) to follow:
208 mode = JSON_STATE_ARRAY_VALUE;
209 // continue with common code for opening JSON object and JSON array:
210 // common code for opening JSON object or JSON array:
211 json_import_open:
212 // limit nested levels:
213 if (level >= JSON_MAXDEPTH) {
214 lua_pushnil(L);
215 lua_pushliteral(L, "Too many nested JSON levels");
216 return 2;
217 }
218 // additional buffer overflow protection:
219 if (!lua_checkstack(L, LUA_MINSTACK))
220 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
221 // increment level:
222 level++;
223 // consume input character:
224 pos++;
225 goto json_import_loop;
226 // end of JSON object:
227 case '}':
228 // if end of JSON object is not expected here, then return an error:
229 if (
230 mode != JSON_STATE_OBJECT_KEY &&
231 mode != JSON_STATE_OBJECT_SEPARATOR
232 ) goto json_import_syntax_error;
233 // jump to common code for end of JSON object and JSON array:
234 goto json_import_close;
235 // end of JSON array:
236 case ']':
237 // if end of JSON array is not expected here, then return an error:
238 if (
239 mode != JSON_STATE_ARRAY_VALUE &&
240 mode != JSON_STATE_ARRAY_SEPARATOR
241 ) goto json_import_syntax_error;
242 // pop nil key/magic (that was needed to keep stack balance):
243 lua_pop(L, 1);
244 // continue with common code for end of JSON object and JSON array:
245 // common code for end of JSON object or JSON array:
246 json_import_close:
247 // consume input character:
248 pos++;
249 // pop shadow table:
250 lua_pop(L, 1);
251 // check if nested:
252 if (--level) {
253 // if nested,
254 // check if outer(!) structure is an array or object:
255 if (lua_isnil(L, -2)) {
256 // select array value processing:
257 mode = JSON_STATE_ARRAY_VALUE;
258 } else {
259 // select object value processing:
260 mode = JSON_STATE_OBJECT_VALUE;
261 }
262 // store value in outer structure:
263 goto json_import_process_value;
264 }
265 // if not nested, then expect end of JSON document and continue with loop:
266 mode = JSON_STATE_END;
267 goto json_import_loop;
268 // key terminator:
269 case ':':
270 // if key terminator is not expected here, then return an error:
271 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
272 goto json_import_syntax_error;
273 // consume input character:
274 pos++;
275 // expect object value to follow:
276 mode = JSON_STATE_OBJECT_VALUE;
277 // continue with loop:
278 goto json_import_loop;
279 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
280 case ',':
281 // branch according to parser state:
282 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
283 // expect an object key to follow:
284 mode = JSON_STATE_OBJECT_KEY;
285 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
286 // expect an array value to follow:
287 mode = JSON_STATE_ARRAY_VALUE;
288 } else {
289 // if value terminator is not expected here, then return an error:
290 goto json_import_syntax_error;
291 }
292 // consume input character:
293 pos++;
294 // continue with loop:
295 goto json_import_loop;
296 // string literal:
297 case '"':
298 // consume quote character:
299 pos++;
300 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
301 cbuf = luaL_buffinitsize(L, &luabuf, total-pos);
302 writepos = 0;
303 // loop through the characters until encountering end quote:
304 while ((c = str[pos++]) != '"') {
305 if (c == 0) {
306 // handle unexpected end of JSON document:
307 goto json_import_unexpected_eof;
308 } else if (c < 32 || c == 127) {
309 // do not allow ASCII control characters:
310 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
311 // by this parser to allow different encodings than Unicode
312 lua_pushnil(L);
313 lua_pushliteral(L, "Unexpected control character in JSON string");
314 return 2;
315 } else if (c == '\\') {
316 // read next char after backslash escape:
317 c = str[pos++];
318 switch (c) {
319 // unexpected end-of-string:
320 case 0:
321 goto json_import_unexpected_eof;
322 // unescaping of quotation mark, slash, and backslash:
323 case '"':
324 case '/':
325 case '\\':
326 cbuf[writepos++] = c;
327 break;
328 // unescaping of backspace:
329 case 'b': cbuf[writepos++] = '\b'; break;
330 // unescaping of form-feed:
331 case 'f': cbuf[writepos++] = '\f'; break;
332 // unescaping of new-line:
333 case 'n': cbuf[writepos++] = '\n'; break;
334 // unescaping of carriage-return:
335 case 'r': cbuf[writepos++] = '\r'; break;
336 // unescaping of tabulator:
337 case 't': cbuf[writepos++] = '\t'; break;
338 // unescaping of UTF-16 characters
339 case 'u':
340 lua_pushnil(L);
341 lua_pushliteral(L, "JSON unicode escape sequences are not implemented yet"); // TODO
342 return 2;
343 // unexpected escape sequence:
344 default:
345 lua_pushnil(L);
346 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
347 return 2;
348 }
349 } else {
350 // normal character:
351 cbuf[writepos++] = c;
352 }
353 }
354 // process buffer to Lua string:
355 luaL_pushresultsize(&luabuf, writepos);
356 // continue with processing of decoded string:
357 goto json_import_process_value;
358 }
359 // process values whose type is is not deducible from a single character:
360 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
361 // for numbers,
362 // use strtod() call to parse a (double precision) floating point number:
363 char *endptr;
364 double numval;
365 numval = strtod(str+pos, &endptr);
366 // catch parsing errors:
367 if (endptr == str+pos) goto json_import_syntax_error;
368 // consume characters that were parsed:
369 pos += endptr - (str+pos);
370 // push parsed (double precision) floating point number on Lua stack:
371 lua_pushnumber(L, numval);
372 } else if (!strncmp(str+pos, "true", 4)) {
373 // consume 4 input characters for "true":
374 pos += 4;
375 // put Lua true value onto stack:
376 lua_pushboolean(L, 1);
377 } else if (!strncmp(str+pos, "false", 5)) {
378 // consume 5 input characters for "false":
379 pos += 5;
380 // put Lua false value onto stack:
381 lua_pushboolean(L, 0);
382 } else if (!strncmp(str+pos, "null", 4)) {
383 // consume 4 input characters for "null":
384 pos += 4;
385 // different behavor for top-level and sub-levels:
386 if (level) {
387 // if sub-level,
388 // push special null-marker onto stack:
389 json_pushnullmark(L);
390 } else {
391 // if top-level,
392 // push nil onto stack:
393 lua_pushnil(L);
394 }
395 } else {
396 // all other cases are a syntax error:
397 goto json_import_syntax_error;
398 }
399 // process a decoded value or key value pair (expected on top of Lua stack):
400 json_import_process_value:
401 switch (mode) {
402 // an object key has been read:
403 case JSON_STATE_OBJECT_KEY:
404 // if an object key is not a string, then this is a syntax error:
405 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
406 // expect key terminator to follow:
407 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
408 // continue with loop:
409 goto json_import_loop;
410 // a key value pair has been read:
411 case JSON_STATE_OBJECT_VALUE:
412 // store key value pair in outer shadow table:
413 lua_rawset(L, -3);
414 // expect value terminator (or end of object) to follow:
415 mode = JSON_STATE_OBJECT_SEPARATOR;
416 // continue with loop:
417 goto json_import_loop;
418 // an array value has been read:
419 case JSON_STATE_ARRAY_VALUE:
420 // get current array length:
421 arraylen = lua_rawlen(L, -3);
422 // throw error if array would exceed INT_MAX elements:
423 // TODO: Lua 5.3 may support more elements
424 if (arraylen >= INT_MAX) {
425 lua_pushnil(L);
426 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
427 }
428 // store value in outer shadow table:
429 lua_rawseti(L, -3, arraylen + 1);
430 // expect value terminator (or end of object) to follow:
431 mode = JSON_STATE_ARRAY_SEPARATOR;
432 // continue with loop
433 goto json_import_loop;
434 // a single value has been read:
435 case JSON_STATE_VALUE:
436 // leave value on top of stack, expect end of JSON document, and continue with loop:
437 mode = JSON_STATE_END;
438 goto json_import_loop;
439 }
440 // syntax error handling (reachable by goto statement):
441 json_import_syntax_error:
442 lua_pushnil(L);
443 lua_pushliteral(L, "Syntax error in JSON document");
444 return 2;
445 }
447 // special Lua stack indicies for json_path function:
448 #define json_path_shadowtbl_idx 1
450 // stack offset of arguments to json_path function:
451 #define json_path_idxshift 1
453 // gets a value or its type from a JSON document (passed as first argument)
454 // using a path (passed as variable number of keys after first argument):
455 static int json_path(lua_State *L, int type_mode) {
456 int stacktop; // stack index of top of stack (after shifting)
457 int idx = 2 + json_path_idxshift; // stack index of current argument to process
458 // insert shadowtbl into stack at position 1 (shifting the arguments):
459 json_regfetch(L, shadowtbl);
460 lua_insert(L, 1);
461 // store stack index of top of stack:
462 stacktop = lua_gettop(L);
463 // use first argument as "current value" (stored on top of stack):
464 lua_pushvalue(L, 1 + json_path_idxshift);
465 // process each "path key" (2nd argument and following arguments):
466 while (idx <= stacktop) {
467 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
468 if (lua_isnil(L, -1)) return 1;
469 // try to get shadow table of "current value":
470 lua_pushvalue(L, -1);
471 lua_rawget(L, json_path_shadowtbl_idx);
472 if (lua_isnil(L, -1)) {
473 // if no shadow table is found,
474 if (lua_type(L, -1) == LUA_TTABLE) {
475 // and if "current value" is a table,
476 // drop nil from stack:
477 lua_pop(L, 1);
478 // get "next value" using the "path key":
479 lua_pushvalue(L, idx++);
480 lua_gettable(L, -2);
481 } else {
482 // if "current value" is not a table,
483 // then the path cannot be walked and nil (already on top of stack) is returned:
484 return 1;
485 }
486 } else {
487 // if a shadow table is found,
488 // set "current value" to its shadow table:
489 lua_replace(L, -2);
490 // get "next value" using the "path key":
491 lua_pushvalue(L, idx++);
492 lua_rawget(L, -2);
493 }
494 // the "next value" replaces the "current value":
495 lua_replace(L, -2);
496 }
497 if (!type_mode) {
498 // if a value (and not its type) was requested,
499 // check if value is the null-marker, and store nil on top of Lua stack in that case:
500 if (json_isnullmark(L, -1)) lua_pushnil(L);
501 } else {
502 // if the type was requested,
503 // check if value is the null-marker:
504 if (json_isnullmark(L, -1)) {
505 // if yes, store string "null" on top of Lua stack:
506 lua_pushliteral(L, "null");
507 } else {
508 // otherwise,
509 // check if metatable indicates "object" or "array":
510 if (lua_getmetatable(L, -1)) {
511 json_regfetch(L, objectmt);
512 if (lua_rawequal(L, -2, -1)) {
513 // if value has metatable for JSON objects,
514 // return string "object":
515 lua_pushliteral(L, "object");
516 return 1;
517 }
518 json_regfetch(L, arraymt);
519 if (lua_rawequal(L, -3, -1)) {
520 // if value has metatable for JSON arrays,
521 // return string "object":
522 lua_pushliteral(L, "array");
523 return 1;
524 }
525 // remove 3 metatables (one of the value, two for comparison) from stack:
526 lua_pop(L, 3);
527 }
528 // otherwise, get the Lua type:
529 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
530 }
531 }
532 // return the top most value on the Lua stack:
533 return 1;
534 }
536 // gets a value from a JSON document (passed as first argument)
537 // using a path (passed as variable number of keys after first argument):
538 static int json_get(lua_State *L) {
539 return json_path(L, 0);
540 }
542 // gets a value's type from a JSON document (passed as first argument)
543 // using a path (variable number of keys after first argument):
544 static int json_type(lua_State *L) {
545 return json_path(L, 1);
546 }
548 // checks if a value in a JSON document (first argument) is
549 // explicitly set to null:
550 static int json_isnull(lua_State *L) {
551 const char *jsontype;
552 // call json_type function with variable arguments:
553 lua_pushcfunction(L, json_type);
554 lua_insert(L, 1);
555 lua_call(L, lua_gettop(L) - 1, 1);
556 // return true if result equals to string "null", otherwise return false:
557 jsontype = lua_tostring(L, -1);
558 if (jsontype && !strcmp(jsontype, "null")) lua_pushboolean(L, 1);
559 else lua_pushboolean(L, 0);
560 return 1;
561 }
563 // returns the length of a JSON array (or zero for a table without numeric keys):
564 static int json_len(lua_State *L) {
565 // stack shall contain one function argument:
566 lua_settop(L, 1);
567 // try to get corresponding shadow table for first argument:
568 json_regfetch(L, shadowtbl);
569 lua_pushvalue(L, 1);
570 lua_rawget(L, -2);
571 // if shadow table does not exist, return length of argument, else length of shadow table:
572 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
573 return 1;
574 }
576 static int json_index(lua_State *L) {
577 // stack shall contain two function arguments:
578 lua_settop(L, 2);
579 // get corresponding shadow table for first argument:
580 json_regfetch(L, shadowtbl);
581 lua_pushvalue(L, 1);
582 lua_rawget(L, -2);
583 // throw error if no shadow table was found:
584 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
585 // use key passed as second argument to lookup value in shadow table:
586 lua_pushvalue(L, 2);
587 lua_rawget(L, -2);
588 // if value is null-marker, then push nil onto stack:
589 if (json_isnullmark(L, -1)) lua_pushnil(L);
590 // return either looked up value, or nil
591 return 1;
592 }
594 static int json_newindex(lua_State *L) {
595 // stack shall contain three function arguments:
596 lua_settop(L, 3);
597 // get corresponding shadow table for first argument:
598 json_regfetch(L, shadowtbl);
599 lua_pushvalue(L, 1);
600 lua_rawget(L, -2);
601 // throw error if no shadow table was found:
602 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
603 // replace first argument with shadow table:
604 lua_replace(L, 1);
605 // reset stack and use second and third argument to write to shadow table:
606 lua_settop(L, 3);
607 lua_rawset(L, 1);
608 // return nothing:
609 return 0;
610 }
612 static int json_pairs_iterfunc(lua_State *L) {
613 // stack shall contain two function arguments:
614 lua_settop(L, 2);
615 // get corresponding shadow table for first argument:
616 json_regfetch(L, shadowtbl);
617 lua_pushvalue(L, 1);
618 lua_rawget(L, -2);
619 // throw error if no shadow table was found:
620 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
621 // get next key value pair from shadow table (using previous key from argument 2)
622 // and return nothing if there is no next pair:
623 lua_pushvalue(L, 2);
624 if (!lua_next(L, -2)) return 0;
625 // replace null-marker with nil:
626 if (json_isnullmark(L, -1)) {
627 lua_pop(L, 1);
628 lua_pushnil(L);
629 }
630 // return key and value (or key and nil, if null-marker was found):
631 return 2;
632 }
634 // returns a triple such that 'for key, value in pairs(obj) do ... end'
635 // iterates through all key value pairs (including JSON null keys represented as Lua nil):
636 static int json_pairs(lua_State *L) {
637 // return triple of function json_pairs_iterfunc, first argument, and nil:
638 lua_pushcfunction(L, json_pairs_iterfunc);
639 lua_pushvalue(L, 1);
640 lua_pushnil(L);
641 return 3;
642 }
644 static int json_ipairs_iterfunc(lua_State *L) {
645 lua_Integer idx;
646 // stack shall contain two function arguments:
647 lua_settop(L, 2);
648 // calculate new index by incrementing second argument:
649 idx = lua_tointeger(L, 2) + 1;
650 // get corresponding shadow table for first argument:
651 json_regfetch(L, shadowtbl);
652 lua_pushvalue(L, 1);
653 lua_rawget(L, -2);
654 // throw error if no shadow table was found:
655 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
656 // do integer lookup in shadow table:
657 lua_rawgeti(L, -1, idx);
658 // return nothing if there was no value:
659 if (lua_isnil(L, -1)) return 0;
660 // return new index and
661 // either the looked up value if it is not equal to the null-marker
662 // or nil instead of null-marker:
663 lua_pushinteger(L, idx);
664 if (json_isnullmark(L, -2)) lua_pushnil(L);
665 else lua_pushvalue(L, -2);
666 return 2;
667 }
669 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
670 // iterates through all values (including JSON null represented as Lua nil):
671 static int json_ipairs(lua_State *L) {
672 // return triple of function json_ipairs_iterfunc, first argument, and zero:
673 lua_pushcfunction(L, json_ipairs_iterfunc);
674 lua_pushvalue(L, 1);
675 lua_pushinteger(L, 0);
676 return 3;
677 }
679 #define JSON_TABLETYPE_UNKNOWN 0
680 #define JSON_TABLETYPE_OBJECT 1
681 #define JSON_TABLETYPE_ARRAY 2
683 static int json_export(lua_State *L) {
684 lua_Number num;
685 const char *str;
686 unsigned char c;
687 size_t strlen;
688 size_t pos = 0;
689 luaL_Buffer buf;
690 char hexcode[7]; // backslash, character 'u', 4 hex digits, and terminating NULL byte
691 int luatype;
692 int tabletype = JSON_TABLETYPE_UNKNOWN;
693 int needsep = 0;
694 lua_Integer idx;
695 lua_settop(L, 1);
696 if (json_isnullmark(L, 1)) {
697 lua_pushnil(L);
698 lua_replace(L, 1);
699 }
700 switch (lua_type(L, 1)) {
701 case LUA_TNIL:
702 lua_pushliteral(L, "null");
703 return 1;
704 case LUA_TNUMBER:
705 num = lua_tonumber(L, 1);
706 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
707 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
708 lua_tostring(L, 1);
709 return 1;
710 case LUA_TBOOLEAN:
711 if (lua_toboolean(L, 1)) lua_pushliteral(L, "true");
712 else lua_pushliteral(L, "false");
713 return 1;
714 case LUA_TSTRING:
715 str = lua_tolstring(L, 1, &strlen);
716 luaL_buffinit(L, &buf);
717 luaL_addchar(&buf, '"');
718 while (pos < strlen) {
719 c = str[pos++];
720 if (c == '"') luaL_addstring(&buf, "\\\"");
721 else if (c == '\\') luaL_addstring(&buf, "\\\\");
722 else if (c == 127) luaL_addstring(&buf, "\\u007F");
723 else if (c >= 32) luaL_addchar(&buf, c);
724 else if (c == '\b') luaL_addstring(&buf, "\\b");
725 else if (c == '\f') luaL_addstring(&buf, "\\f");
726 else if (c == '\n') luaL_addstring(&buf, "\\n");
727 else if (c == '\r') luaL_addstring(&buf, "\\r");
728 else if (c == '\t') luaL_addstring(&buf, "\\t");
729 else if (c == '\v') luaL_addstring(&buf, "\\v");
730 else {
731 sprintf(hexcode, "\\u%04X", c);
732 luaL_addstring(&buf, hexcode);
733 }
734 }
735 luaL_addchar(&buf, '"');
736 luaL_pushresult(&buf);
737 return 1;
738 case LUA_TTABLE:
739 if (lua_getmetatable(L, 1)) {
740 json_regfetch(L, objectmt);
741 if (lua_rawequal(L, -2, -1)) {
742 tabletype = JSON_TABLETYPE_OBJECT;
743 } else {
744 json_regfetch(L, arraymt);
745 if (lua_rawequal(L, -3, -1)) tabletype = JSON_TABLETYPE_ARRAY;
746 }
747 }
748 json_regfetch(L, shadowtbl);
749 lua_pushvalue(L, 1);
750 lua_rawget(L, -2);
751 if (!lua_isnil(L, -1)) lua_replace(L, 1);
752 lua_settop(L, 1);
753 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
754 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
755 luatype = lua_type(L, -2);
756 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
757 if (luatype == LUA_TSTRING) tabletype = JSON_TABLETYPE_OBJECT;
758 else if (luatype == LUA_TNUMBER) tabletype = JSON_TABLETYPE_ARRAY;
759 } else if (
760 (tabletype == JSON_TABLETYPE_OBJECT && luatype == LUA_TNUMBER) ||
761 (tabletype == JSON_TABLETYPE_ARRAY && luatype == LUA_TSTRING)
762 ) {
763 goto json_export_tabletype_error;
764 }
765 }
766 }
767 switch (tabletype) {
768 case JSON_TABLETYPE_OBJECT:
769 lua_settop(L, 3);
770 luaL_buffinit(L, &buf);
771 luaL_addchar(&buf, '{');
772 for (lua_pushnil(L); lua_next(L, 1); ) {
773 if (lua_type(L, -2) == LUA_TSTRING) {
774 lua_replace(L, 3);
775 lua_replace(L, 2);
776 if (needsep) luaL_addchar(&buf, ',');
777 else needsep = 1;
778 lua_pushcfunction(L, json_export);
779 lua_pushvalue(L, 2);
780 lua_call(L, 1, 1);
781 luaL_addvalue(&buf);
782 luaL_addchar(&buf, ':');
783 if (json_isnullmark(L, 3)) {
784 luaL_addstring(&buf, "null");
785 } else {
786 lua_pushcfunction(L, json_export);
787 lua_pushvalue(L, 3);
788 lua_call(L, 1, 1);
789 luaL_addvalue(&buf);
790 }
791 lua_pushvalue(L, 2);
792 } else {
793 lua_pop(L, 1);
794 }
795 }
796 luaL_addchar(&buf, '}');
797 luaL_pushresult(&buf);
798 return 1;
799 case JSON_TABLETYPE_ARRAY:
800 lua_settop(L, 2);
801 luaL_buffinit(L, &buf);
802 luaL_addchar(&buf, '[');
803 for (idx = 1; ; idx++) {
804 lua_rawgeti(L, 1, idx);
805 if (lua_isnil(L, -1)) {
806 lua_pop(L, 1);
807 break;
808 }
809 lua_replace(L, 2);
810 if (needsep) luaL_addchar(&buf, ',');
811 else needsep = 1;
812 lua_pushcfunction(L, json_export);
813 lua_pushvalue(L, 2);
814 lua_call(L, 1, 1);
815 luaL_addvalue(&buf);
816 }
817 luaL_addchar(&buf, ']');
818 luaL_pushresult(&buf);
819 return 1;
820 }
821 json_export_tabletype_error:
822 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
823 }
824 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, 1)));
825 }
827 // functions in library module:
828 static const struct luaL_Reg json_module_functions[] = {
829 {"object", json_object},
830 {"array", json_array},
831 {"import", json_import},
832 {"export", json_export},
833 {"get", json_get},
834 {"type", json_type},
835 {"isnull", json_isnull},
836 {NULL, NULL}
837 };
839 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
840 static const struct luaL_Reg json_metatable_functions[] = {
841 {"__len", json_len},
842 {"__index", json_index},
843 {"__newindex", json_newindex},
844 {"__pairs", json_pairs},
845 {"__ipairs", json_ipairs},
846 {NULL, NULL}
847 };
849 // metamethods for JSON null marker:
850 static const struct luaL_Reg json_nullmark_metamethods[] = {
851 {"__tostring", json_nullmark_tostring},
852 {NULL, NULL}
853 };
855 // initializes json library:
856 int luaopen_json(lua_State *L) {
857 // empty stack:
858 lua_settop(L, 0);
859 // push library module onto stack position 1:
860 lua_newtable(L);
861 // register library functions:
862 luaL_setfuncs(L, json_module_functions, 0);
863 // create and store objectmt:
864 lua_newtable(L);
865 luaL_setfuncs(L, json_metatable_functions, 0);
866 json_regstore(L, objectmt);
867 // create and store arraymt:
868 lua_newtable(L);
869 luaL_setfuncs(L, json_metatable_functions, 0);
870 json_regstore(L, arraymt);
871 // create and store ephemeron table to store shadow tables for each JSON object/array
872 // to allow NULL values returned as nil
873 lua_newtable(L);
874 lua_newtable(L); // metatable for ephemeron table
875 lua_pushliteral(L, "__mode");
876 lua_pushliteral(L, "k");
877 lua_rawset(L, -3);
878 lua_setmetatable(L, -2);
879 json_regstore(L, shadowtbl);
880 // set metatable of null marker and make it available through library module:
881 json_pushnullmark(L);
882 lua_newtable(L);
883 luaL_setfuncs(L, json_nullmark_metamethods, 0);
884 lua_setmetatable(L, -2);
885 lua_setfield(L, 1, "null");
886 // return library module (that's expected on top of stack):
887 return 1;
888 }