webmcp

annotate libraries/json/json.c @ 168:e618ccd017a3

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

Impressum / About Us