webmcp

view libraries/json/json.c @ 155:185e944182cb

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

Impressum / About Us