webmcp

annotate libraries/json/json.c @ 166:7885d1ae35ff

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

Impressum / About Us