webmcp

view libraries/json/json.c @ 159:ddb9b9b0d210

Removed json.isnull function from JSON library (use json.type(...) == "null" instead)
author jbe
date Thu Jul 31 03:54:57 2014 +0200 (2014-07-31)
parents d42a7a840358
children d5e5e8a9b79a
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 // returns the length of a JSON array (or zero for a table without numeric keys):
549 static int json_len(lua_State *L) {
550 // stack shall contain one function argument:
551 lua_settop(L, 1);
552 // try to get corresponding shadow table for first argument:
553 json_regfetch(L, shadowtbl);
554 lua_pushvalue(L, 1);
555 lua_rawget(L, -2);
556 // if shadow table does not exist, return length of argument, else length of shadow table:
557 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
558 return 1;
559 }
561 static int json_index(lua_State *L) {
562 // stack shall contain two function arguments:
563 lua_settop(L, 2);
564 // get corresponding shadow table for first argument:
565 json_regfetch(L, shadowtbl);
566 lua_pushvalue(L, 1);
567 lua_rawget(L, -2);
568 // throw error if no shadow table was found:
569 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
570 // use key passed as second argument to lookup value in shadow table:
571 lua_pushvalue(L, 2);
572 lua_rawget(L, -2);
573 // if value is null-marker, then push nil onto stack:
574 if (json_isnullmark(L, -1)) lua_pushnil(L);
575 // return either looked up value, or nil
576 return 1;
577 }
579 static int json_newindex(lua_State *L) {
580 // stack shall contain three function arguments:
581 lua_settop(L, 3);
582 // get corresponding shadow table for first argument:
583 json_regfetch(L, shadowtbl);
584 lua_pushvalue(L, 1);
585 lua_rawget(L, -2);
586 // throw error if no shadow table was found:
587 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
588 // replace first argument with shadow table:
589 lua_replace(L, 1);
590 // reset stack and use second and third argument to write to shadow table:
591 lua_settop(L, 3);
592 lua_rawset(L, 1);
593 // return nothing:
594 return 0;
595 }
597 static int json_pairs_iterfunc(lua_State *L) {
598 // stack shall contain two function arguments:
599 lua_settop(L, 2);
600 // get corresponding shadow table for first argument:
601 json_regfetch(L, shadowtbl);
602 lua_pushvalue(L, 1);
603 lua_rawget(L, -2);
604 // throw error if no shadow table was found:
605 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
606 // get next key value pair from shadow table (using previous key from argument 2)
607 // and return nothing if there is no next pair:
608 lua_pushvalue(L, 2);
609 if (!lua_next(L, -2)) return 0;
610 // replace null-marker with nil:
611 if (json_isnullmark(L, -1)) {
612 lua_pop(L, 1);
613 lua_pushnil(L);
614 }
615 // return key and value (or key and nil, if null-marker was found):
616 return 2;
617 }
619 // returns a triple such that 'for key, value in pairs(obj) do ... end'
620 // iterates through all key value pairs (including JSON null keys represented as Lua nil):
621 static int json_pairs(lua_State *L) {
622 // return triple of function json_pairs_iterfunc, first argument, and nil:
623 lua_pushcfunction(L, json_pairs_iterfunc);
624 lua_pushvalue(L, 1);
625 lua_pushnil(L);
626 return 3;
627 }
629 static int json_ipairs_iterfunc(lua_State *L) {
630 lua_Integer idx;
631 // stack shall contain two function arguments:
632 lua_settop(L, 2);
633 // calculate new index by incrementing second argument:
634 idx = lua_tointeger(L, 2) + 1;
635 // get corresponding shadow table for first argument:
636 json_regfetch(L, shadowtbl);
637 lua_pushvalue(L, 1);
638 lua_rawget(L, -2);
639 // throw error if no shadow table was found:
640 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
641 // do integer lookup in shadow table:
642 lua_rawgeti(L, -1, idx);
643 // return nothing if there was no value:
644 if (lua_isnil(L, -1)) return 0;
645 // return new index and
646 // either the looked up value if it is not equal to the null-marker
647 // or nil instead of null-marker:
648 lua_pushinteger(L, idx);
649 if (json_isnullmark(L, -2)) lua_pushnil(L);
650 else lua_pushvalue(L, -2);
651 return 2;
652 }
654 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
655 // iterates through all values (including JSON null represented as Lua nil):
656 static int json_ipairs(lua_State *L) {
657 // return triple of function json_ipairs_iterfunc, first argument, and zero:
658 lua_pushcfunction(L, json_ipairs_iterfunc);
659 lua_pushvalue(L, 1);
660 lua_pushinteger(L, 0);
661 return 3;
662 }
664 #define JSON_TABLETYPE_UNKNOWN 0
665 #define JSON_TABLETYPE_OBJECT 1
666 #define JSON_TABLETYPE_ARRAY 2
668 static int json_export(lua_State *L) {
669 lua_Number num;
670 const char *str;
671 unsigned char c;
672 size_t strlen;
673 size_t pos = 0;
674 luaL_Buffer buf;
675 char hexcode[7]; // backslash, character 'u', 4 hex digits, and terminating NULL byte
676 int luatype;
677 int tabletype = JSON_TABLETYPE_UNKNOWN;
678 int needsep = 0;
679 lua_Integer idx;
680 lua_settop(L, 1);
681 if (json_isnullmark(L, 1)) {
682 lua_pushnil(L);
683 lua_replace(L, 1);
684 }
685 switch (lua_type(L, 1)) {
686 case LUA_TNIL:
687 lua_pushliteral(L, "null");
688 return 1;
689 case LUA_TNUMBER:
690 num = lua_tonumber(L, 1);
691 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
692 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
693 lua_tostring(L, 1);
694 return 1;
695 case LUA_TBOOLEAN:
696 if (lua_toboolean(L, 1)) lua_pushliteral(L, "true");
697 else lua_pushliteral(L, "false");
698 return 1;
699 case LUA_TSTRING:
700 str = lua_tolstring(L, 1, &strlen);
701 luaL_buffinit(L, &buf);
702 luaL_addchar(&buf, '"');
703 while (pos < strlen) {
704 c = str[pos++];
705 if (c == '"') luaL_addstring(&buf, "\\\"");
706 else if (c == '\\') luaL_addstring(&buf, "\\\\");
707 else if (c == 127) luaL_addstring(&buf, "\\u007F");
708 else if (c >= 32) luaL_addchar(&buf, c);
709 else if (c == '\b') luaL_addstring(&buf, "\\b");
710 else if (c == '\f') luaL_addstring(&buf, "\\f");
711 else if (c == '\n') luaL_addstring(&buf, "\\n");
712 else if (c == '\r') luaL_addstring(&buf, "\\r");
713 else if (c == '\t') luaL_addstring(&buf, "\\t");
714 else if (c == '\v') luaL_addstring(&buf, "\\v");
715 else {
716 sprintf(hexcode, "\\u%04X", c);
717 luaL_addstring(&buf, hexcode);
718 }
719 }
720 luaL_addchar(&buf, '"');
721 luaL_pushresult(&buf);
722 return 1;
723 case LUA_TTABLE:
724 if (lua_getmetatable(L, 1)) {
725 json_regfetch(L, objectmt);
726 if (lua_rawequal(L, -2, -1)) {
727 tabletype = JSON_TABLETYPE_OBJECT;
728 } else {
729 json_regfetch(L, arraymt);
730 if (lua_rawequal(L, -3, -1)) tabletype = JSON_TABLETYPE_ARRAY;
731 }
732 }
733 json_regfetch(L, shadowtbl);
734 lua_pushvalue(L, 1);
735 lua_rawget(L, -2);
736 if (!lua_isnil(L, -1)) lua_replace(L, 1);
737 lua_settop(L, 1);
738 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
739 for (lua_pushnil(L); lua_next(L, 1); lua_pop(L, 1)) {
740 luatype = lua_type(L, -2);
741 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
742 if (luatype == LUA_TSTRING) tabletype = JSON_TABLETYPE_OBJECT;
743 else if (luatype == LUA_TNUMBER) tabletype = JSON_TABLETYPE_ARRAY;
744 } else if (
745 (tabletype == JSON_TABLETYPE_OBJECT && luatype == LUA_TNUMBER) ||
746 (tabletype == JSON_TABLETYPE_ARRAY && luatype == LUA_TSTRING)
747 ) {
748 goto json_export_tabletype_error;
749 }
750 }
751 }
752 switch (tabletype) {
753 case JSON_TABLETYPE_OBJECT:
754 lua_settop(L, 3);
755 luaL_buffinit(L, &buf);
756 luaL_addchar(&buf, '{');
757 for (lua_pushnil(L); lua_next(L, 1); ) {
758 if (lua_type(L, -2) == LUA_TSTRING) {
759 lua_replace(L, 3);
760 lua_replace(L, 2);
761 if (needsep) luaL_addchar(&buf, ',');
762 else needsep = 1;
763 lua_pushcfunction(L, json_export);
764 lua_pushvalue(L, 2);
765 lua_call(L, 1, 1);
766 luaL_addvalue(&buf);
767 luaL_addchar(&buf, ':');
768 if (json_isnullmark(L, 3)) {
769 luaL_addstring(&buf, "null");
770 } else {
771 lua_pushcfunction(L, json_export);
772 lua_pushvalue(L, 3);
773 lua_call(L, 1, 1);
774 luaL_addvalue(&buf);
775 }
776 lua_pushvalue(L, 2);
777 } else {
778 lua_pop(L, 1);
779 }
780 }
781 luaL_addchar(&buf, '}');
782 luaL_pushresult(&buf);
783 return 1;
784 case JSON_TABLETYPE_ARRAY:
785 lua_settop(L, 2);
786 luaL_buffinit(L, &buf);
787 luaL_addchar(&buf, '[');
788 for (idx = 1; ; idx++) {
789 lua_rawgeti(L, 1, idx);
790 if (lua_isnil(L, -1)) {
791 lua_pop(L, 1);
792 break;
793 }
794 lua_replace(L, 2);
795 if (needsep) luaL_addchar(&buf, ',');
796 else needsep = 1;
797 lua_pushcfunction(L, json_export);
798 lua_pushvalue(L, 2);
799 lua_call(L, 1, 1);
800 luaL_addvalue(&buf);
801 }
802 luaL_addchar(&buf, ']');
803 luaL_pushresult(&buf);
804 return 1;
805 }
806 json_export_tabletype_error:
807 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
808 }
809 return luaL_error(L, "JSON export not possible for values of type \"%s\"", lua_typename(L, lua_type(L, 1)));
810 }
812 // functions in library module:
813 static const struct luaL_Reg json_module_functions[] = {
814 {"object", json_object},
815 {"array", json_array},
816 {"import", json_import},
817 {"export", json_export},
818 {"get", json_get},
819 {"type", json_type},
820 {NULL, NULL}
821 };
823 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
824 static const struct luaL_Reg json_metatable_functions[] = {
825 {"__len", json_len},
826 {"__index", json_index},
827 {"__newindex", json_newindex},
828 {"__pairs", json_pairs},
829 {"__ipairs", json_ipairs},
830 {NULL, NULL}
831 };
833 // metamethods for JSON null marker:
834 static const struct luaL_Reg json_nullmark_metamethods[] = {
835 {"__tostring", json_nullmark_tostring},
836 {NULL, NULL}
837 };
839 // initializes json library:
840 int luaopen_json(lua_State *L) {
841 // empty stack:
842 lua_settop(L, 0);
843 // push library module onto stack position 1:
844 lua_newtable(L);
845 // register library functions:
846 luaL_setfuncs(L, json_module_functions, 0);
847 // create and store objectmt:
848 lua_newtable(L);
849 luaL_setfuncs(L, json_metatable_functions, 0);
850 json_regstore(L, objectmt);
851 // create and store arraymt:
852 lua_newtable(L);
853 luaL_setfuncs(L, json_metatable_functions, 0);
854 json_regstore(L, arraymt);
855 // create and store ephemeron table to store shadow tables for each JSON object/array
856 // to allow NULL values returned as nil
857 lua_newtable(L);
858 lua_newtable(L); // metatable for ephemeron table
859 lua_pushliteral(L, "__mode");
860 lua_pushliteral(L, "k");
861 lua_rawset(L, -3);
862 lua_setmetatable(L, -2);
863 json_regstore(L, shadowtbl);
864 // set metatable of null marker and make it available through library module:
865 json_pushnullmark(L);
866 lua_newtable(L);
867 luaL_setfuncs(L, json_nullmark_metamethods, 0);
868 lua_setmetatable(L, -2);
869 lua_setfield(L, 1, "null");
870 // return library module (that's expected on top of stack):
871 return 1;
872 }

Impressum / About Us