webmcp

annotate libraries/json/json.c @ 179:461e5353ffb1

Limit max depth of JSON documents to 50 (until a better implementation of json.export is available)
author jbe
date Sat Aug 02 00:38:25 2014 +0200 (2014-08-02)
parents 20e393d2e6e1
children 887b77f71e5e
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@179 16 // NOTE: As long as the function json_export_internal is implemented
jbe@179 17 // recursively, JSON_MAXDEPTH needs to be low (e.g. 50) to avoid C stack
jbe@179 18 // overflows.
jbe@179 19 #if JSON_MAXDEPTH > 50
jbe@179 20 #define JSON_MAXDEPTH 50
jbe@179 21 #endif
jbe@142 22
jbe@155 23 // generate dummy memory addresses that represents null values:
jbe@155 24 char json_nullmark;
jbe@155 25 #define json_isnullmark(L, i) (lua_touserdata((L), (i)) == &json_nullmark)
jbe@155 26 #define json_pushnullmark(L) lua_pushlightuserdata((L), &json_nullmark)
jbe@155 27
jbe@144 28 // macros for usage of Lua registry:
jbe@144 29 #define JSON_REGENT char
jbe@145 30 #define JSON_REGPOINTER void *
jbe@145 31 #define json_regpointer(x) (&json_registry.x)
jbe@151 32 #define json_regfetchpointer(L, x) lua_rawgetp((L), LUA_REGISTRYINDEX, (x))
jbe@151 33 #define json_regfetch(L, x) json_regfetchpointer(L, json_regpointer(x))
jbe@151 34 #define json_regstore(L, x) lua_rawsetp(L, LUA_REGISTRYINDEX, json_regpointer(x))
jbe@145 35
jbe@144 36 // generate dummy memory addresses that represent Lua objects
jbe@145 37 // via lightuserdata keys and LUA_REGISTRYINDEX:
jbe@144 38 static struct {
jbe@145 39 JSON_REGENT shadowtbl; // ephemeron table that maps tables to their corresponding shadow table
jbe@145 40 JSON_REGENT objectmt; // metatable for JSON objects
jbe@145 41 JSON_REGENT arraymt; // metatable for JSON arrays
jbe@144 42 } json_registry;
jbe@138 43
jbe@157 44 // returns the string "<JSON null marker>":
jbe@157 45 static int json_nullmark_tostring(lua_State *L) {
jbe@157 46 lua_pushliteral(L, "<JSON null marker>");
jbe@157 47 return 1;
jbe@157 48 }
jbe@157 49
jbe@169 50 #define json_convert_source_idx 1
jbe@169 51 #define json_convert_iterator_idx 2
jbe@169 52 #define json_convert_output_idx 3
jbe@169 53 #define json_convert_shadow_idx 4
jbe@172 54 #define json_convert_iterfun_idx 5
jbe@172 55 #define json_convert_itertbl_idx 6
jbe@169 56
jbe@175 57 // converts a Lua table (or any other iterable value) to a JSON object or JSON array:
jbe@169 58 // (does never modify the argument, returns an empty object or array if argument is nil)
jbe@169 59 static int json_convert(lua_State *L, int array) {
jbe@171 60 int arrayidx = 0;
jbe@171 61 // determine is argument is given:
jbe@169 62 if (lua_isnoneornil(L, json_convert_source_idx)) {
jbe@171 63 // if no argument is given (or if argument is nil),
jbe@171 64 // create table with shadow table, and leave first table on top of stack:
jbe@144 65 json_regfetch(L, shadowtbl);
jbe@169 66 lua_newtable(L);
jbe@169 67 lua_pushvalue(L, -1);
jbe@169 68 lua_newtable(L);
jbe@169 69 lua_rawset(L, -4);
jbe@169 70 } else {
jbe@171 71 // if an argument was given,
jbe@171 72 // push its iterator function on stack position 2 if existent,
jbe@169 73 // else push null for normal tables:
jbe@171 74 lua_settop(L, 1);
jbe@169 75 if (lua_getmetatable(L, json_convert_source_idx)) {
jbe@169 76 lua_getfield(L, -1, array ? "__ipairs" : "__pairs");
jbe@169 77 if (lua_isnil(L, -1)) luaL_checktype(L, 1, LUA_TTABLE);
jbe@169 78 else if (lua_type(L, -1) != LUA_TFUNCTION)
jbe@169 79 return luaL_error(L, "%s metamethod is not a function", array ? "__ipairs" : "__pairs");
jbe@169 80 lua_replace(L, -2);
jbe@169 81 } else {
jbe@169 82 lua_pushnil(L);
jbe@143 83 }
jbe@171 84 // create result table on stack position 3:
jbe@169 85 lua_newtable(L);
jbe@169 86 // create shadow table on stack position 4:
jbe@169 87 json_regfetch(L, shadowtbl);
jbe@169 88 lua_newtable(L);
jbe@169 89 lua_pushvalue(L, json_convert_output_idx);
jbe@169 90 lua_pushvalue(L, -2);
jbe@169 91 lua_rawset(L, -4);
jbe@169 92 lua_replace(L, -2);
jbe@171 93 // check if iterator function exists:
jbe@169 94 if (lua_isnil(L, json_convert_iterator_idx)) {
jbe@171 95 // if there is no iterator function,
jbe@171 96 // distinguish between objects and arrays:
jbe@171 97 if (array == 0) {
jbe@171 98 // for an object, copy all string key value pairs to shadow table:
jbe@171 99 for (lua_pushnil(L); lua_next(L, json_convert_source_idx); lua_pop(L, 1)) {
jbe@171 100 if (lua_type(L, -2) == LUA_TSTRING) {
jbe@171 101 lua_pushvalue(L, -2);
jbe@171 102 lua_pushvalue(L, -2);
jbe@171 103 lua_rawset(L, json_convert_shadow_idx);
jbe@171 104 }
jbe@171 105 }
jbe@171 106 } else {
jbe@171 107 // for an array, copy consecutive integer value pairs to shadow table:
jbe@171 108 while (1) {
jbe@175 109 // throw error if array would exceed INT_MAX elements:
jbe@171 110 // TODO: Lua 5.3 may support more elements
jbe@171 111 if (arrayidx == INT_MAX) {
jbe@171 112 lua_pushnumber(L, (size_t)INT_MAX+1);
jbe@171 113 lua_rawget(L, json_convert_source_idx);
jbe@171 114 if (lua_isnil(L, -1)) break;
jbe@171 115 return luaL_error(L, "Array exceeded length of %d elements", INT_MAX);
jbe@171 116 }
jbe@175 117 // get next array entry:
jbe@171 118 arrayidx++;
jbe@171 119 lua_rawgeti(L, json_convert_source_idx, arrayidx);
jbe@175 120 // break if value is nil:
jbe@171 121 if (lua_isnil(L, -1)) break;
jbe@175 122 // store value in shadow table:
jbe@171 123 lua_rawseti(L, json_convert_shadow_idx, arrayidx);
jbe@171 124 }
jbe@169 125 }
jbe@169 126 } else {
jbe@172 127 // if there is an iterator function,
jbe@172 128 // call iterator function with source value (first argument)
jbe@172 129 // and store 3 result values on stack positions 5 through 7:
jbe@172 130 lua_pushvalue(L, json_convert_iterator_idx);
jbe@172 131 lua_pushvalue(L, 1);
jbe@172 132 lua_call(L, 1, 3);
jbe@175 133 // iterate through key value pairs and store some of them in shadow table
jbe@174 134 // while replacing nil values with null-marker:
jbe@172 135 while (1) {
jbe@175 136 // call iterfun function:
jbe@172 137 lua_pushvalue(L, json_convert_iterfun_idx);
jbe@172 138 lua_pushvalue(L, json_convert_itertbl_idx);
jbe@172 139 lua_pushvalue(L, -3);
jbe@172 140 lua_remove(L, -4);
jbe@172 141 lua_call(L, 2, 2);
jbe@175 142 // break iteration loop if key is nil:
jbe@172 143 if (lua_isnil(L, -2)) break;
jbe@175 144 // store key value pair only if key type is correct:
jbe@172 145 if (lua_type(L, -2) == (array ? LUA_TNUMBER : LUA_TSTRING)) {
jbe@175 146 // if key type is correct,
jbe@175 147 // push key onto stack:
jbe@172 148 lua_pushvalue(L, -2);
jbe@175 149 // if value is nil, push null-marker onto stack (as value):
jbe@174 150 if (lua_isnil(L, -2)) json_pushnullmark(L);
jbe@175 151 // else push value onto stack:
jbe@174 152 else lua_pushvalue(L, -2);
jbe@175 153 // set key value pair in shadow table:
jbe@172 154 lua_rawset(L, json_convert_shadow_idx);
jbe@172 155 }
jbe@175 156 // pop value from stack, but leave key on stack:
jbe@172 157 lua_pop(L, 1);
jbe@172 158 }
jbe@143 159 }
jbe@171 160 // let result table be on top of stack:
jbe@169 161 lua_settop(L, json_convert_output_idx);
jbe@136 162 }
jbe@171 163 // set metatable (for result table on top of stack):
jbe@171 164 if (array == 0) json_regfetch(L, objectmt);
jbe@171 165 else json_regfetch(L, arraymt);
jbe@169 166 lua_setmetatable(L, -2);
jbe@171 167 // return table on top of stack:
jbe@136 168 return 1;
jbe@136 169 }
jbe@136 170
jbe@175 171 // converts a Lua table (or any other iterable value) to a JSON object:
jbe@175 172 // (does never modify the argument, returns an empty object or array if argument is nil)
jbe@136 173 static int json_object(lua_State *L) {
jbe@169 174 return json_convert(L, 0);
jbe@136 175 }
jbe@136 176
jbe@175 177 // converts a Lua table (or any other iterable value) to a JSON array:
jbe@175 178 // (does never modify the argument, returns an empty object or array if argument is nil)
jbe@136 179 static int json_array(lua_State *L) {
jbe@169 180 return json_convert(L, 1);
jbe@136 181 }
jbe@136 182
jbe@145 183 // internal states of JSON parser:
jbe@124 184 #define JSON_STATE_VALUE 0
jbe@124 185 #define JSON_STATE_OBJECT_KEY 1
jbe@124 186 #define JSON_STATE_OBJECT_KEY_TERMINATOR 2
jbe@124 187 #define JSON_STATE_OBJECT_VALUE 3
jbe@124 188 #define JSON_STATE_OBJECT_SEPARATOR 4
jbe@124 189 #define JSON_STATE_ARRAY_VALUE 5
jbe@124 190 #define JSON_STATE_ARRAY_SEPARATOR 6
jbe@124 191 #define JSON_STATE_END 7
jbe@121 192
jbe@145 193 // special Lua stack indicies for json_import function:
jbe@138 194 #define json_import_objectmt_idx 2
jbe@138 195 #define json_import_arraymt_idx 3
jbe@138 196 #define json_import_shadowtbl_idx 4
jbe@138 197
jbe@168 198 // macros for hex decoding:
jbe@168 199 #define json_utf16_surrogate(x) ((x) >= 0xD800 && (x) <= 0xDFFF)
jbe@168 200 #define json_utf16_lead(x) ((x) >= 0xD800 && (x) <= 0xDBFF)
jbe@168 201 #define json_utf16_tail(x) ((x) >= 0xDC00 && (x) <= 0xDFFF)
jbe@167 202 #define json_import_readhex(x) \
jbe@167 203 do { \
jbe@167 204 x = 0; \
jbe@167 205 for (i=0; i<4; i++) { \
jbe@167 206 x <<= 4; \
jbe@167 207 c = str[pos++]; \
jbe@167 208 if (c >= '0' && c <= '9') x += c - '0'; \
jbe@167 209 else if (c >= 'A' && c <= 'F') x += c - 'A' + 10; \
jbe@167 210 else if (c >= 'a' && c <= 'f') x += c - 'a' + 10; \
jbe@167 211 else if (c == 0) goto json_import_unexpected_eof; \
jbe@167 212 else goto json_import_unexpected_escape; \
jbe@167 213 } \
jbe@167 214 } while (0)
jbe@167 215
jbe@136 216 // decodes a JSON document:
jbe@121 217 static int json_import(lua_State *L) {
jbe@167 218 int i; // loop variable
jbe@136 219 const char *str; // string to parse
jbe@136 220 size_t total; // total length of string to parse
jbe@136 221 size_t pos = 0; // current position in string to parse
jbe@136 222 size_t level = 0; // nested levels of objects/arrays currently being processed
jbe@145 223 int mode = JSON_STATE_VALUE; // state of parser (i.e. "what's expected next?")
jbe@170 224 unsigned char c; // variable to store a single character to be processed (unsigned!)
jbe@145 225 luaL_Buffer luabuf; // Lua buffer to decode JSON string values
jbe@145 226 char *cbuf; // C buffer to decode JSON string values
jbe@162 227 size_t outlen; // maximum length or write position of C buffer
jbe@167 228 long codepoint; // decoded UTF-16 character or higher codepoint
jbe@167 229 long utf16tail; // second decoded UTF-16 character (surrogate tail)
jbe@152 230 size_t arraylen; // variable to temporarily store the array length
jbe@166 231 // require string as argument and convert to C string with length information:
jbe@166 232 str = luaL_checklstring(L, 1, &total);
jbe@166 233 // if string contains a NULL byte, this is a syntax error
jbe@166 234 if (strlen(str) != total) goto json_import_syntax_error;
jbe@147 235 // stack shall contain one function argument:
jbe@138 236 lua_settop(L, 1);
jbe@147 237 // push objectmt onto stack position 2:
jbe@144 238 json_regfetch(L, objectmt);
jbe@147 239 // push arraymt onto stack position 3:
jbe@144 240 json_regfetch(L, arraymt);
jbe@147 241 // push shadowtbl onto stack position 4:
jbe@144 242 json_regfetch(L, shadowtbl);
jbe@136 243 // main loop of parser:
jbe@136 244 json_import_loop:
jbe@136 245 // skip whitespace and store next character in variable 'c':
jbe@146 246 while (c = str[pos],
jbe@146 247 c == ' ' ||
jbe@146 248 c == '\f' ||
jbe@146 249 c == '\n' ||
jbe@146 250 c == '\r' ||
jbe@146 251 c == '\t' ||
jbe@146 252 c == '\v'
jbe@146 253 ) pos++;
jbe@170 254 // NOTE: variable c needs to be unsigned in the following code
jbe@136 255 // switch statement to handle certain (single) characters:
jbe@121 256 switch (c) {
jbe@136 257 // handle end of JSON document:
jbe@121 258 case 0:
jbe@136 259 // if end of JSON document was expected, then return top element of stack as result:
jbe@124 260 if (mode == JSON_STATE_END) return 1;
jbe@136 261 // otherwise, the JSON document was malformed:
jbe@167 262 if (level == 0) {
jbe@167 263 lua_pushnil(L);
jbe@167 264 lua_pushliteral(L, "Empty string");
jbe@167 265 } else {
jbe@167 266 json_import_unexpected_eof:
jbe@167 267 lua_pushnil(L);
jbe@167 268 lua_pushliteral(L, "Unexpected end of JSON document");
jbe@167 269 }
jbe@121 270 return 2;
jbe@136 271 // new JSON object:
jbe@121 272 case '{':
jbe@136 273 // if a JSON object is not expected here, then return an error:
jbe@146 274 if (
jbe@146 275 mode != JSON_STATE_VALUE &&
jbe@146 276 mode != JSON_STATE_OBJECT_VALUE &&
jbe@146 277 mode != JSON_STATE_ARRAY_VALUE
jbe@146 278 ) goto json_import_syntax_error;
jbe@136 279 // create JSON object on stack:
jbe@136 280 lua_newtable(L);
jbe@136 281 // set metatable of JSON object:
jbe@138 282 lua_pushvalue(L, json_import_objectmt_idx);
jbe@125 283 lua_setmetatable(L, -2);
jbe@136 284 // create internal shadow table on stack:
jbe@136 285 lua_newtable(L);
jbe@146 286 // register internal shadow table:
jbe@123 287 lua_pushvalue(L, -2);
jbe@123 288 lua_pushvalue(L, -2);
jbe@138 289 lua_rawset(L, json_import_shadowtbl_idx);
jbe@146 290 // expect object key (or end of object) to follow:
jbe@136 291 mode = JSON_STATE_OBJECT_KEY;
jbe@146 292 // jump to common code for opening JSON object and JSON array:
jbe@142 293 goto json_import_open;
jbe@136 294 // new JSON array:
jbe@121 295 case '[':
jbe@136 296 // if a JSON array is not expected here, then return an error:
jbe@146 297 if (
jbe@146 298 mode != JSON_STATE_VALUE &&
jbe@146 299 mode != JSON_STATE_OBJECT_VALUE &&
jbe@146 300 mode != JSON_STATE_ARRAY_VALUE
jbe@146 301 ) goto json_import_syntax_error;
jbe@136 302 // create JSON array on stack:
jbe@136 303 lua_newtable(L);
jbe@136 304 // set metatable of JSON array:
jbe@138 305 lua_pushvalue(L, json_import_arraymt_idx);
jbe@125 306 lua_setmetatable(L, -2);
jbe@136 307 // create internal shadow table on stack:
jbe@136 308 lua_newtable(L);
jbe@146 309 // register internal shadow table:
jbe@123 310 lua_pushvalue(L, -2);
jbe@123 311 lua_pushvalue(L, -2);
jbe@138 312 lua_rawset(L, json_import_shadowtbl_idx);
jbe@140 313 // add nil as key (needed to keep stack balance) and as magic to detect arrays:
jbe@140 314 lua_pushnil(L);
jbe@146 315 // expect array value (or end of array) to follow:
jbe@142 316 mode = JSON_STATE_ARRAY_VALUE;
jbe@142 317 // continue with common code for opening JSON object and JSON array:
jbe@146 318 // common code for opening JSON object or JSON array:
jbe@142 319 json_import_open:
jbe@142 320 // limit nested levels:
jbe@142 321 if (level >= JSON_MAXDEPTH) {
jbe@142 322 lua_pushnil(L);
jbe@164 323 lua_pushfstring(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
jbe@142 324 return 2;
jbe@142 325 }
jbe@142 326 // additional buffer overflow protection:
jbe@142 327 if (!lua_checkstack(L, LUA_MINSTACK))
jbe@142 328 return luaL_error(L, "Caught stack overflow in JSON import function (too many nested levels and stack size too small)");
jbe@136 329 // increment level:
jbe@121 330 level++;
jbe@142 331 // consume input character:
jbe@142 332 pos++;
jbe@121 333 goto json_import_loop;
jbe@136 334 // end of JSON object:
jbe@121 335 case '}':
jbe@136 336 // if end of JSON object is not expected here, then return an error:
jbe@146 337 if (
jbe@146 338 mode != JSON_STATE_OBJECT_KEY &&
jbe@146 339 mode != JSON_STATE_OBJECT_SEPARATOR
jbe@146 340 ) goto json_import_syntax_error;
jbe@136 341 // jump to common code for end of JSON object and JSON array:
jbe@121 342 goto json_import_close;
jbe@136 343 // end of JSON array:
jbe@121 344 case ']':
jbe@136 345 // if end of JSON array is not expected here, then return an error:
jbe@146 346 if (
jbe@146 347 mode != JSON_STATE_ARRAY_VALUE &&
jbe@146 348 mode != JSON_STATE_ARRAY_SEPARATOR
jbe@146 349 ) goto json_import_syntax_error;
jbe@146 350 // pop nil key/magic (that was needed to keep stack balance):
jbe@140 351 lua_pop(L, 1);
jbe@136 352 // continue with common code for end of JSON object and JSON array:
jbe@136 353 // common code for end of JSON object or JSON array:
jbe@121 354 json_import_close:
jbe@136 355 // consume input character:
jbe@121 356 pos++;
jbe@136 357 // pop shadow table:
jbe@136 358 lua_pop(L, 1);
jbe@136 359 // check if nested:
jbe@121 360 if (--level) {
jbe@146 361 // if nested,
jbe@146 362 // check if outer(!) structure is an array or object:
jbe@140 363 if (lua_isnil(L, -2)) {
jbe@136 364 // select array value processing:
jbe@124 365 mode = JSON_STATE_ARRAY_VALUE;
jbe@121 366 } else {
jbe@136 367 // select object value processing:
jbe@124 368 mode = JSON_STATE_OBJECT_VALUE;
jbe@121 369 }
jbe@136 370 // store value in outer structure:
jbe@121 371 goto json_import_process_value;
jbe@121 372 }
jbe@136 373 // if not nested, then expect end of JSON document and continue with loop:
jbe@136 374 mode = JSON_STATE_END;
jbe@121 375 goto json_import_loop;
jbe@136 376 // key terminator:
jbe@121 377 case ':':
jbe@136 378 // if key terminator is not expected here, then return an error:
jbe@124 379 if (mode != JSON_STATE_OBJECT_KEY_TERMINATOR)
jbe@121 380 goto json_import_syntax_error;
jbe@136 381 // consume input character:
jbe@121 382 pos++;
jbe@146 383 // expect object value to follow:
jbe@124 384 mode = JSON_STATE_OBJECT_VALUE;
jbe@146 385 // continue with loop:
jbe@121 386 goto json_import_loop;
jbe@136 387 // value terminator (NOTE: trailing comma at end of value or key-value list is tolerated by this parser)
jbe@121 388 case ',':
jbe@146 389 // branch according to parser state:
jbe@124 390 if (mode == JSON_STATE_OBJECT_SEPARATOR) {
jbe@146 391 // expect an object key to follow:
jbe@124 392 mode = JSON_STATE_OBJECT_KEY;
jbe@124 393 } else if (mode == JSON_STATE_ARRAY_SEPARATOR) {
jbe@146 394 // expect an array value to follow:
jbe@124 395 mode = JSON_STATE_ARRAY_VALUE;
jbe@121 396 } else {
jbe@136 397 // if value terminator is not expected here, then return an error:
jbe@136 398 goto json_import_syntax_error;
jbe@121 399 }
jbe@136 400 // consume input character:
jbe@121 401 pos++;
jbe@136 402 // continue with loop:
jbe@121 403 goto json_import_loop;
jbe@136 404 // string literal:
jbe@121 405 case '"':
jbe@146 406 // consume quote character:
jbe@146 407 pos++;
jbe@162 408 // find last character in input string:
jbe@162 409 outlen = pos;
jbe@162 410 while ((c = str[outlen]) != '"') {
jbe@161 411 // consume one character:
jbe@162 412 outlen++;
jbe@161 413 // handle unexpected end of JSON document:
jbe@161 414 if (c == 0) goto json_import_unexpected_eof;
jbe@161 415 // consume one extra character when encountering an escaped quote:
jbe@162 416 else if (c == '\\' && str[outlen] == '"') outlen++;
jbe@161 417 }
jbe@162 418 // determine buffer length:
jbe@162 419 outlen -= pos;
jbe@161 420 // check if string is non empty:
jbe@162 421 if (outlen) {
jbe@161 422 // prepare buffer to decode string (with maximum possible length) and set write position to zero:
jbe@162 423 cbuf = luaL_buffinitsize(L, &luabuf, outlen);
jbe@162 424 outlen = 0;
jbe@161 425 // loop through the characters until encountering end quote:
jbe@161 426 while ((c = str[pos++]) != '"') {
jbe@162 427 // NOTE: unexpected end cannot happen anymore
jbe@162 428 if (c < 32 || c == 127) {
jbe@161 429 // do not allow ASCII control characters:
jbe@161 430 // NOTE: illegal UTF-8 sequences and extended control characters are not sanitized
jbe@161 431 // by this parser to allow different encodings than Unicode
jbe@161 432 lua_pushnil(L);
jbe@161 433 lua_pushliteral(L, "Unexpected control character in JSON string");
jbe@161 434 return 2;
jbe@161 435 } else if (c == '\\') {
jbe@161 436 // read next char after backslash escape:
jbe@161 437 c = str[pos++];
jbe@161 438 switch (c) {
jbe@161 439 // unexpected end-of-string:
jbe@161 440 case 0:
jbe@161 441 goto json_import_unexpected_eof;
jbe@161 442 // unescaping of quotation mark, slash, and backslash:
jbe@161 443 case '"':
jbe@161 444 case '/':
jbe@161 445 case '\\':
jbe@162 446 cbuf[outlen++] = c;
jbe@161 447 break;
jbe@161 448 // unescaping of backspace:
jbe@162 449 case 'b': cbuf[outlen++] = '\b'; break;
jbe@161 450 // unescaping of form-feed:
jbe@162 451 case 'f': cbuf[outlen++] = '\f'; break;
jbe@161 452 // unescaping of new-line:
jbe@162 453 case 'n': cbuf[outlen++] = '\n'; break;
jbe@161 454 // unescaping of carriage-return:
jbe@162 455 case 'r': cbuf[outlen++] = '\r'; break;
jbe@161 456 // unescaping of tabulator:
jbe@162 457 case 't': cbuf[outlen++] = '\t'; break;
jbe@161 458 // unescaping of UTF-16 characters
jbe@161 459 case 'u':
jbe@167 460 // decode 4 hex nibbles:
jbe@167 461 json_import_readhex(codepoint);
jbe@167 462 // handle surrogate character:
jbe@167 463 if (json_utf16_surrogate(codepoint)) {
jbe@167 464 // check if first surrogate is in valid range:
jbe@167 465 if (json_utf16_lead(codepoint)) {
jbe@167 466 // require second surrogate:
jbe@167 467 if ((c = str[pos++]) != '\\' || (c = str[pos++]) != 'u') {
jbe@167 468 if (c == 0) goto json_import_unexpected_eof;
jbe@167 469 else goto json_import_wrong_surrogate;
jbe@167 470 }
jbe@167 471 // read 4 hex nibbles of second surrogate character:
jbe@167 472 json_import_readhex(utf16tail);
jbe@167 473 // check if second surrogate is in valid range:
jbe@167 474 if (!json_utf16_tail(utf16tail)) goto json_import_wrong_surrogate;
jbe@167 475 // calculate codepoint:
jbe@167 476 codepoint = 0x10000 + (utf16tail - 0xDC00) + (codepoint - 0xD800) * 0x400;
jbe@167 477 } else {
jbe@167 478 // throw error for wrong surrogates:
jbe@167 479 json_import_wrong_surrogate:
jbe@167 480 lua_pushnil(L);
jbe@167 481 lua_pushliteral(L, "Illegal UTF-16 surrogate in JSON string escape sequence");
jbe@167 482 return 2;
jbe@167 483 }
jbe@167 484 }
jbe@167 485 // encode as UTF-8:
jbe@167 486 if (codepoint < 0x80) {
jbe@167 487 cbuf[outlen++] = (char)codepoint;
jbe@167 488 } else if (codepoint < 0x800) {
jbe@167 489 cbuf[outlen++] = (char)(0xc0 | (codepoint >> 6));
jbe@167 490 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
jbe@167 491 } else if (codepoint < 0x10000) {
jbe@167 492 cbuf[outlen++] = (char)(0xe0 | (codepoint >> 12));
jbe@167 493 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
jbe@167 494 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
jbe@167 495 } else {
jbe@167 496 cbuf[outlen++] = (char)(0xf0 | (codepoint >> 18));
jbe@167 497 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 12) & 0x3f));
jbe@167 498 cbuf[outlen++] = (char)(0x80 | ((codepoint >> 6) & 0x3f));
jbe@167 499 cbuf[outlen++] = (char)(0x80 | (codepoint & 0x3f));
jbe@167 500 }
jbe@167 501 break;
jbe@161 502 // unexpected escape sequence:
jbe@161 503 default:
jbe@167 504 json_import_unexpected_escape:
jbe@161 505 lua_pushnil(L);
jbe@161 506 lua_pushliteral(L, "Unexpected string escape sequence in JSON document");
jbe@161 507 return 2;
jbe@161 508 }
jbe@161 509 } else {
jbe@161 510 // normal character:
jbe@162 511 cbuf[outlen++] = c;
jbe@121 512 }
jbe@121 513 }
jbe@161 514 // process buffer to Lua string:
jbe@162 515 luaL_pushresultsize(&luabuf, outlen);
jbe@161 516 } else {
jbe@161 517 // if JSON string is empty,
jbe@161 518 // push empty Lua string:
jbe@161 519 lua_pushliteral(L, "");
jbe@167 520 // consume closing quote:
jbe@167 521 pos++;
jbe@121 522 }
jbe@136 523 // continue with processing of decoded string:
jbe@121 524 goto json_import_process_value;
jbe@121 525 }
jbe@136 526 // process values whose type is is not deducible from a single character:
jbe@136 527 if ((c >= '0' && c <= '9') || c == '-' || c == '+') {
jbe@146 528 // for numbers,
jbe@146 529 // use strtod() call to parse a (double precision) floating point number:
jbe@167 530 double numval;
jbe@122 531 char *endptr;
jbe@122 532 numval = strtod(str+pos, &endptr);
jbe@146 533 // catch parsing errors:
jbe@122 534 if (endptr == str+pos) goto json_import_syntax_error;
jbe@146 535 // consume characters that were parsed:
jbe@122 536 pos += endptr - (str+pos);
jbe@146 537 // push parsed (double precision) floating point number on Lua stack:
jbe@122 538 lua_pushnumber(L, numval);
jbe@122 539 } else if (!strncmp(str+pos, "true", 4)) {
jbe@136 540 // consume 4 input characters for "true":
jbe@121 541 pos += 4;
jbe@147 542 // put Lua true value onto stack:
jbe@136 543 lua_pushboolean(L, 1);
jbe@121 544 } else if (!strncmp(str+pos, "false", 5)) {
jbe@136 545 // consume 5 input characters for "false":
jbe@121 546 pos += 5;
jbe@147 547 // put Lua false value onto stack:
jbe@136 548 lua_pushboolean(L, 0);
jbe@121 549 } else if (!strncmp(str+pos, "null", 4)) {
jbe@136 550 // consume 4 input characters for "null":
jbe@136 551 pos += 4;
jbe@153 552 // different behavor for top-level and sub-levels:
jbe@153 553 if (level) {
jbe@153 554 // if sub-level,
jbe@153 555 // push special null-marker onto stack:
jbe@155 556 json_pushnullmark(L);
jbe@153 557 } else {
jbe@153 558 // if top-level,
jbe@153 559 // push nil onto stack:
jbe@153 560 lua_pushnil(L);
jbe@153 561 }
jbe@121 562 } else {
jbe@136 563 // all other cases are a syntax error:
jbe@121 564 goto json_import_syntax_error;
jbe@121 565 }
jbe@136 566 // process a decoded value or key value pair (expected on top of Lua stack):
jbe@136 567 json_import_process_value:
jbe@121 568 switch (mode) {
jbe@136 569 // an object key has been read:
jbe@124 570 case JSON_STATE_OBJECT_KEY:
jbe@136 571 // if an object key is not a string, then this is a syntax error:
jbe@121 572 if (lua_type(L, -1) != LUA_TSTRING) goto json_import_syntax_error;
jbe@146 573 // expect key terminator to follow:
jbe@124 574 mode = JSON_STATE_OBJECT_KEY_TERMINATOR;
jbe@146 575 // continue with loop:
jbe@121 576 goto json_import_loop;
jbe@136 577 // a key value pair has been read:
jbe@124 578 case JSON_STATE_OBJECT_VALUE:
jbe@136 579 // store key value pair in outer shadow table:
jbe@130 580 lua_rawset(L, -3);
jbe@146 581 // expect value terminator (or end of object) to follow:
jbe@124 582 mode = JSON_STATE_OBJECT_SEPARATOR;
jbe@146 583 // continue with loop:
jbe@121 584 goto json_import_loop;
jbe@136 585 // an array value has been read:
jbe@124 586 case JSON_STATE_ARRAY_VALUE:
jbe@152 587 // get current array length:
jbe@152 588 arraylen = lua_rawlen(L, -3);
jbe@152 589 // throw error if array would exceed INT_MAX elements:
jbe@152 590 // TODO: Lua 5.3 may support more elements
jbe@152 591 if (arraylen >= INT_MAX) {
jbe@152 592 lua_pushnil(L);
jbe@152 593 lua_pushfstring(L, "Array exceeded length of %d elements", INT_MAX);
jbe@152 594 }
jbe@136 595 // store value in outer shadow table:
jbe@152 596 lua_rawseti(L, -3, arraylen + 1);
jbe@146 597 // expect value terminator (or end of object) to follow:
jbe@124 598 mode = JSON_STATE_ARRAY_SEPARATOR;
jbe@146 599 // continue with loop
jbe@121 600 goto json_import_loop;
jbe@136 601 // a single value has been read:
jbe@124 602 case JSON_STATE_VALUE:
jbe@136 603 // leave value on top of stack, expect end of JSON document, and continue with loop:
jbe@124 604 mode = JSON_STATE_END;
jbe@121 605 goto json_import_loop;
jbe@121 606 }
jbe@146 607 // syntax error handling (reachable by goto statement):
jbe@136 608 json_import_syntax_error:
jbe@121 609 lua_pushnil(L);
jbe@121 610 lua_pushliteral(L, "Syntax error in JSON document");
jbe@121 611 return 2;
jbe@121 612 }
jbe@121 613
jbe@146 614 // special Lua stack indicies for json_path function:
jbe@138 615 #define json_path_shadowtbl_idx 1
jbe@146 616
jbe@146 617 // stack offset of arguments to json_path function:
jbe@155 618 #define json_path_idxshift 1
jbe@138 619
jbe@146 620 // gets a value or its type from a JSON document (passed as first argument)
jbe@175 621 // using a path (passed as variable number of keys after the first argument):
jbe@137 622 static int json_path(lua_State *L, int type_mode) {
jbe@146 623 int stacktop; // stack index of top of stack (after shifting)
jbe@146 624 int idx = 2 + json_path_idxshift; // stack index of current argument to process
jbe@173 625 // require at least one argument:
jbe@173 626 luaL_checkany(L, 1);
jbe@148 627 // insert shadowtbl into stack at position 1 (shifting the arguments):
jbe@144 628 json_regfetch(L, shadowtbl);
jbe@138 629 lua_insert(L, 1);
jbe@146 630 // store stack index of top of stack:
jbe@138 631 stacktop = lua_gettop(L);
jbe@146 632 // use first argument as "current value" (stored on top of stack):
jbe@138 633 lua_pushvalue(L, 1 + json_path_idxshift);
jbe@146 634 // process each "path key" (2nd argument and following arguments):
jbe@138 635 while (idx <= stacktop) {
jbe@146 636 // if "current value" (on top of stack) is nil, then the path cannot be walked and nil is returned:
jbe@137 637 if (lua_isnil(L, -1)) return 1;
jbe@137 638 // try to get shadow table of "current value":
jbe@130 639 lua_pushvalue(L, -1);
jbe@138 640 lua_rawget(L, json_path_shadowtbl_idx);
jbe@126 641 if (lua_isnil(L, -1)) {
jbe@137 642 // if no shadow table is found,
jbe@130 643 if (lua_type(L, -1) == LUA_TTABLE) {
jbe@146 644 // and if "current value" is a table,
jbe@146 645 // drop nil from stack:
jbe@146 646 lua_pop(L, 1);
jbe@137 647 // get "next value" using the "path key":
jbe@130 648 lua_pushvalue(L, idx++);
jbe@130 649 lua_gettable(L, -2);
jbe@130 650 } else {
jbe@137 651 // if "current value" is not a table,
jbe@146 652 // then the path cannot be walked and nil (already on top of stack) is returned:
jbe@137 653 return 1;
jbe@130 654 }
jbe@130 655 } else {
jbe@137 656 // if a shadow table is found,
jbe@137 657 // set "current value" to its shadow table:
jbe@130 658 lua_replace(L, -2);
jbe@137 659 // get "next value" using the "path key":
jbe@130 660 lua_pushvalue(L, idx++);
jbe@130 661 lua_rawget(L, -2);
jbe@126 662 }
jbe@137 663 // the "next value" replaces the "current value":
jbe@130 664 lua_replace(L, -2);
jbe@126 665 }
jbe@137 666 if (!type_mode) {
jbe@137 667 // if a value (and not its type) was requested,
jbe@137 668 // check if value is the null-marker, and store nil on top of Lua stack in that case:
jbe@155 669 if (json_isnullmark(L, -1)) lua_pushnil(L);
jbe@137 670 } else {
jbe@137 671 // if the type was requested,
jbe@137 672 // check if value is the null-marker:
jbe@155 673 if (json_isnullmark(L, -1)) {
jbe@137 674 // if yes, store string "null" on top of Lua stack:
jbe@130 675 lua_pushliteral(L, "null");
jbe@137 676 } else {
jbe@137 677 // otherwise,
jbe@138 678 // check if metatable indicates "object" or "array":
jbe@138 679 if (lua_getmetatable(L, -1)) {
jbe@144 680 json_regfetch(L, objectmt);
jbe@138 681 if (lua_rawequal(L, -2, -1)) {
jbe@146 682 // if value has metatable for JSON objects,
jbe@138 683 // return string "object":
jbe@138 684 lua_pushliteral(L, "object");
jbe@138 685 return 1;
jbe@138 686 }
jbe@144 687 json_regfetch(L, arraymt);
jbe@138 688 if (lua_rawequal(L, -3, -1)) {
jbe@146 689 // if value has metatable for JSON arrays,
jbe@146 690 // return string "object":
jbe@138 691 lua_pushliteral(L, "array");
jbe@138 692 return 1;
jbe@138 693 }
jbe@146 694 // remove 3 metatables (one of the value, two for comparison) from stack:
jbe@138 695 lua_pop(L, 3);
jbe@138 696 }
jbe@138 697 // otherwise, get the Lua type:
jbe@138 698 lua_pushstring(L, lua_typename(L, lua_type(L, -1)));
jbe@126 699 }
jbe@126 700 }
jbe@137 701 // return the top most value on the Lua stack:
jbe@137 702 return 1;
jbe@130 703 }
jbe@130 704
jbe@147 705 // gets a value from a JSON document (passed as first argument)
jbe@175 706 // using a path (passed as variable number of keys after the first argument):
jbe@130 707 static int json_get(lua_State *L) {
jbe@137 708 return json_path(L, 0);
jbe@130 709 }
jbe@130 710
jbe@147 711 // gets a value's type from a JSON document (passed as first argument)
jbe@175 712 // using a path (passed as variable number of keys after first the argument):
jbe@130 713 static int json_type(lua_State *L) {
jbe@137 714 return json_path(L, 1);
jbe@130 715 }
jbe@130 716
jbe@173 717 // special Lua stack indicies for json_set function:
jbe@173 718 #define json_set_shadowtbl_idx 1
jbe@173 719 #define json_set_objectmt_idx 2
jbe@173 720 #define json_set_arraymt_idx 3
jbe@173 721
jbe@173 722 // stack offset of arguments to json_set function:
jbe@173 723 #define json_set_idxshift 3
jbe@173 724
jbe@173 725 // sets a value (passed as second argument) in a JSON document (passed as first argument)
jbe@175 726 // using a path (passed as variable number of keys starting at third argument):
jbe@173 727 static int json_set(lua_State *L) {
jbe@173 728 int stacktop; // stack index of top of stack (after shifting)
jbe@173 729 int idx = 3; // stack index of current argument to process
jbe@173 730 // require at least two arguments:
jbe@173 731 luaL_checkany(L, 1);
jbe@173 732 luaL_checkany(L, 2);
jbe@173 733 // insert shadowtbl into stack at position 1 (shifting the arguments):
jbe@173 734 json_regfetch(L, shadowtbl);
jbe@173 735 lua_insert(L, 1);
jbe@173 736 // insert objectmt into stack at position 2 (shifting the arguments):
jbe@173 737 json_regfetch(L, objectmt);
jbe@173 738 lua_insert(L, 2);
jbe@173 739 // insert arraymt into stack at position 3 (shifting the arguments):
jbe@173 740 json_regfetch(L, arraymt);
jbe@173 741 lua_insert(L, 3);
jbe@173 742 // store stack index of top of stack:
jbe@173 743 stacktop = lua_gettop(L);
jbe@173 744 // use nil as initial "parent value":
jbe@173 745 lua_pushnil(L);
jbe@173 746 // use first argument as "current value":
jbe@173 747 lua_pushvalue(L, 1 + json_set_idxshift);
jbe@173 748 // set all necessary values in path:
jbe@173 749 for (idx = 3 + json_set_idxshift; idx<=stacktop; idx++) {
jbe@173 750 // push metatable of "current value" onto stack:
jbe@173 751 if (!lua_getmetatable(L, -1)) lua_pushnil(L);
jbe@173 752 // distinguish according to type of path key:
jbe@173 753 switch (lua_type(L, idx)) {
jbe@173 754 case LUA_TSTRING:
jbe@173 755 // if path key is a string,
jbe@173 756 // check if "current value" is a JSON object (or table without metatable):
jbe@173 757 if (
jbe@173 758 lua_rawequal(L, -1, json_set_objectmt_idx) ||
jbe@173 759 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
jbe@173 760 ) {
jbe@173 761 // if "current value" is acceptable,
jbe@173 762 // pop metatable and leave "current value" on top of stack:
jbe@173 763 lua_pop(L, 1);
jbe@173 764 } else {
jbe@173 765 // if "current value" is not acceptable:
jbe@173 766 // pop metatable and "current value":
jbe@173 767 lua_pop(L, 2);
jbe@173 768 // throw error if parent element does not exist:
jbe@173 769 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON object");
jbe@173 770 // push new JSON object as "current value" onto stack:
jbe@173 771 lua_newtable(L);
jbe@173 772 // create and register shadow table:
jbe@173 773 lua_pushvalue(L, -1);
jbe@173 774 lua_newtable(L);
jbe@173 775 lua_rawset(L, json_set_shadowtbl_idx);
jbe@173 776 // set metatable of JSON object:
jbe@173 777 lua_pushvalue(L, json_set_objectmt_idx);
jbe@173 778 lua_setmetatable(L, -2);
jbe@173 779 // set entry in "parent value":
jbe@173 780 lua_pushvalue(L, idx-1);
jbe@173 781 lua_pushvalue(L, -2);
jbe@173 782 lua_settable(L, -4);
jbe@173 783 }
jbe@173 784 break;
jbe@173 785 case LUA_TNUMBER:
jbe@173 786 // if path key is a number,
jbe@173 787 // check if "current value" is a JSON array (or table without metatable):
jbe@173 788 if (
jbe@173 789 lua_rawequal(L, -1, json_set_arraymt_idx) ||
jbe@173 790 (lua_isnil(L, -1) && lua_type(L, -2) == LUA_TTABLE)
jbe@173 791 ) {
jbe@173 792 // if "current value" is acceptable,
jbe@173 793 // pop metatable and leave "current value" on top of stack:
jbe@173 794 lua_pop(L, 1);
jbe@173 795 } else {
jbe@173 796 // if "current value" is not acceptable:
jbe@173 797 // pop metatable and "current value":
jbe@173 798 lua_pop(L, 2);
jbe@173 799 // throw error if parent element does not exist:
jbe@173 800 if (lua_isnil(L, -1)) return luaL_error(L, "Root element is not a JSON array");
jbe@173 801 // push new JSON array as "current value" onto stack:
jbe@173 802 lua_newtable(L);
jbe@173 803 // create and register shadow table:
jbe@173 804 lua_pushvalue(L, -1);
jbe@173 805 lua_newtable(L);
jbe@173 806 lua_rawset(L, json_set_shadowtbl_idx);
jbe@173 807 // set metatable of JSON array:
jbe@173 808 lua_pushvalue(L, json_set_arraymt_idx);
jbe@173 809 lua_setmetatable(L, -2);
jbe@173 810 // set entry in "parent value":
jbe@173 811 lua_pushvalue(L, idx-1);
jbe@173 812 lua_pushvalue(L, -2);
jbe@173 813 lua_settable(L, -4);
jbe@173 814 }
jbe@173 815 break;
jbe@173 816 default:
jbe@173 817 return luaL_error(L, "Invalid path key of type %s", lua_typename(L, lua_type(L, idx)));
jbe@173 818 }
jbe@173 819 // check if last path element is being processed:
jbe@173 820 if (idx == stacktop) {
jbe@173 821 // if the last path element is being processed,
jbe@173 822 // set last path value in "current value" container:
jbe@173 823 lua_pushvalue(L, idx);
jbe@173 824 lua_pushvalue(L, 2 + json_set_idxshift);
jbe@173 825 lua_settable(L, -3);
jbe@173 826 } else {
jbe@173 827 // if the processed path element is not the last,
jbe@173 828 // use old "current value" as new "parent value"
jbe@173 829 lua_remove(L, -2);
jbe@173 830 // push new "current value" onto stack by performing a lookup:
jbe@173 831 lua_pushvalue(L, idx);
jbe@173 832 lua_gettable(L, -2);
jbe@173 833 }
jbe@173 834 }
jbe@173 835 // return first argument for convenience:
jbe@173 836 lua_settop(L, 1 + json_set_idxshift);
jbe@173 837 return 1;
jbe@173 838 }
jbe@173 839
jbe@147 840 // returns the length of a JSON array (or zero for a table without numeric keys):
jbe@130 841 static int json_len(lua_State *L) {
jbe@147 842 // stack shall contain one function argument:
jbe@130 843 lua_settop(L, 1);
jbe@148 844 // try to get corresponding shadow table for first argument:
jbe@144 845 json_regfetch(L, shadowtbl);
jbe@130 846 lua_pushvalue(L, 1);
jbe@138 847 lua_rawget(L, -2);
jbe@147 848 // if shadow table does not exist, return length of argument, else length of shadow table:
jbe@147 849 lua_pushnumber(L, lua_rawlen(L, lua_isnil(L, -1) ? 1 : -1));
jbe@123 850 return 1;
jbe@123 851 }
jbe@123 852
jbe@175 853 // __index metamethod for JSON objects and JSON arrays:
jbe@130 854 static int json_index(lua_State *L) {
jbe@148 855 // stack shall contain two function arguments:
jbe@130 856 lua_settop(L, 2);
jbe@155 857 // get corresponding shadow table for first argument:
jbe@144 858 json_regfetch(L, shadowtbl);
jbe@130 859 lua_pushvalue(L, 1);
jbe@155 860 lua_rawget(L, -2);
jbe@148 861 // throw error if no shadow table was found:
jbe@139 862 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
jbe@148 863 // use key passed as second argument to lookup value in shadow table:
jbe@130 864 lua_pushvalue(L, 2);
jbe@130 865 lua_rawget(L, -2);
jbe@148 866 // if value is null-marker, then push nil onto stack:
jbe@155 867 if (json_isnullmark(L, -1)) lua_pushnil(L);
jbe@148 868 // return either looked up value, or nil
jbe@127 869 return 1;
jbe@127 870 }
jbe@127 871
jbe@175 872 // __newindex metamethod for JSON objects and JSON arrays:
jbe@130 873 static int json_newindex(lua_State *L) {
jbe@148 874 // stack shall contain three function arguments:
jbe@130 875 lua_settop(L, 3);
jbe@148 876 // get corresponding shadow table for first argument:
jbe@144 877 json_regfetch(L, shadowtbl);
jbe@123 878 lua_pushvalue(L, 1);
jbe@143 879 lua_rawget(L, -2);
jbe@148 880 // throw error if no shadow table was found:
jbe@130 881 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
jbe@148 882 // replace first argument with shadow table:
jbe@130 883 lua_replace(L, 1);
jbe@148 884 // reset stack and use second and third argument to write to shadow table:
jbe@139 885 lua_settop(L, 3);
jbe@130 886 lua_rawset(L, 1);
jbe@148 887 // return nothing:
jbe@148 888 return 0;
jbe@121 889 }
jbe@121 890
jbe@175 891 // function returned as first value by json_pairs function:
jbe@135 892 static int json_pairs_iterfunc(lua_State *L) {
jbe@149 893 // stack shall contain two function arguments:
jbe@135 894 lua_settop(L, 2);
jbe@155 895 // get corresponding shadow table for first argument:
jbe@144 896 json_regfetch(L, shadowtbl);
jbe@135 897 lua_pushvalue(L, 1);
jbe@155 898 lua_rawget(L, -2);
jbe@149 899 // throw error if no shadow table was found:
jbe@135 900 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
jbe@149 901 // get next key value pair from shadow table (using previous key from argument 2)
jbe@149 902 // and return nothing if there is no next pair:
jbe@135 903 lua_pushvalue(L, 2);
jbe@135 904 if (!lua_next(L, -2)) return 0;
jbe@149 905 // replace null-marker with nil:
jbe@155 906 if (json_isnullmark(L, -1)) {
jbe@135 907 lua_pop(L, 1);
jbe@135 908 lua_pushnil(L);
jbe@135 909 }
jbe@149 910 // return key and value (or key and nil, if null-marker was found):
jbe@135 911 return 2;
jbe@135 912 }
jbe@135 913
jbe@149 914 // returns a triple such that 'for key, value in pairs(obj) do ... end'
jbe@175 915 // iterates through all key value pairs (including JSON null values represented as Lua nil):
jbe@135 916 static int json_pairs(lua_State *L) {
jbe@172 917 // require one argument to function
jbe@172 918 luaL_checkany(L, 1);
jbe@149 919 // return triple of function json_pairs_iterfunc, first argument, and nil:
jbe@139 920 lua_pushcfunction(L, json_pairs_iterfunc);
jbe@135 921 lua_pushvalue(L, 1);
jbe@135 922 lua_pushnil(L);
jbe@135 923 return 3;
jbe@135 924 }
jbe@135 925
jbe@175 926 // function returned as first value by json_ipairs function:
jbe@134 927 static int json_ipairs_iterfunc(lua_State *L) {
jbe@152 928 lua_Integer idx;
jbe@149 929 // stack shall contain two function arguments:
jbe@134 930 lua_settop(L, 2);
jbe@149 931 // calculate new index by incrementing second argument:
jbe@134 932 idx = lua_tointeger(L, 2) + 1;
jbe@149 933 // get corresponding shadow table for first argument:
jbe@155 934 json_regfetch(L, shadowtbl);
jbe@134 935 lua_pushvalue(L, 1);
jbe@155 936 lua_rawget(L, -2);
jbe@149 937 // throw error if no shadow table was found:
jbe@134 938 if (lua_isnil(L, -1)) return luaL_error(L, "Shadow table not found");
jbe@149 939 // do integer lookup in shadow table:
jbe@134 940 lua_rawgeti(L, -1, idx);
jbe@149 941 // return nothing if there was no value:
jbe@134 942 if (lua_isnil(L, -1)) return 0;
jbe@149 943 // return new index and
jbe@149 944 // either the looked up value if it is not equal to the null-marker
jbe@149 945 // or nil instead of null-marker:
jbe@134 946 lua_pushinteger(L, idx);
jbe@155 947 if (json_isnullmark(L, -2)) lua_pushnil(L);
jbe@134 948 else lua_pushvalue(L, -2);
jbe@134 949 return 2;
jbe@134 950 }
jbe@134 951
jbe@149 952 // returns a triple such that 'for idx, value in ipairs(ary) do ... end'
jbe@175 953 // iterates through all values (including JSON null values represented as Lua nil):
jbe@134 954 static int json_ipairs(lua_State *L) {
jbe@172 955 // require one argument to function
jbe@172 956 luaL_checkany(L, 1);
jbe@149 957 // return triple of function json_ipairs_iterfunc, first argument, and zero:
jbe@139 958 lua_pushcfunction(L, json_ipairs_iterfunc);
jbe@134 959 lua_pushvalue(L, 1);
jbe@134 960 lua_pushinteger(L, 0);
jbe@134 961 return 3;
jbe@134 962 }
jbe@134 963
jbe@175 964 // datatype representing a table key:
jbe@175 965 // (used for sorting)
jbe@163 966 typedef struct {
jbe@163 967 size_t length;
jbe@163 968 const char *data;
jbe@163 969 } json_key_t;
jbe@163 970
jbe@175 971 // comparation function for table keys to be passed to qsort function:
jbe@163 972 static int json_key_cmp(json_key_t *key1, json_key_t *key2) {
jbe@163 973 size_t pos = 0;
jbe@163 974 unsigned char c1, c2;
jbe@163 975 while (1) {
jbe@163 976 if (key1->length > pos) {
jbe@163 977 if (key2->length > pos) {
jbe@163 978 c1 = key1->data[pos];
jbe@163 979 c2 = key2->data[pos];
jbe@163 980 if (c1 < c2) return -1;
jbe@163 981 else if (c1 > c2) return 1;
jbe@163 982 } else {
jbe@163 983 return 1;
jbe@163 984 }
jbe@163 985 } else {
jbe@163 986 if (key2->length > pos) {
jbe@163 987 return -1;
jbe@163 988 } else {
jbe@163 989 return 0;
jbe@163 990 }
jbe@163 991 }
jbe@163 992 pos++;
jbe@163 993 }
jbe@163 994 }
jbe@163 995
jbe@175 996 // constants for type detection of ambiguous tables:
jbe@154 997 #define JSON_TABLETYPE_UNKNOWN 0
jbe@154 998 #define JSON_TABLETYPE_OBJECT 1
jbe@154 999 #define JSON_TABLETYPE_ARRAY 2
jbe@154 1000
jbe@175 1001 // special Lua stack indicies for json_export_internal function:
jbe@164 1002 #define json_export_internal_indentstring_idx 1
jbe@164 1003 #define json_export_internal_level_idx 2
jbe@164 1004 #define json_export_internal_value_idx 3
jbe@164 1005 #define json_export_internal_tmp_idx 4
jbe@164 1006
jbe@175 1007 // encodes a JSON document (passed as third argument)
jbe@175 1008 // optionally using indentation (indentation string passed as first argument)
jbe@175 1009 // for a certain depth level (passed as second argument):
jbe@164 1010 static int json_export_internal(lua_State *L) {
jbe@175 1011 int level; // current depth level
jbe@175 1012 int pretty; // pretty printing on? (i.e. printing with indentation)
jbe@175 1013 int i; // iteration variable for level dependent repetitions:
jbe@175 1014 lua_Number num; // number to encode
jbe@175 1015 const char *str; // string to encode
jbe@175 1016 size_t strlen; // length of string to encode
jbe@175 1017 unsigned char c; // character to encode (unsigned!)
jbe@175 1018 size_t pos = 0; // position in string or position of current key (initialized with zero!)
jbe@175 1019 luaL_Buffer buf; // Lua buffer to create strings
jbe@175 1020 char hexcode[7]; // store for unicode hex escape sequence
jbe@175 1021 // NOTE: 7 bytes due to backslash, character 'u', 4 hex digits, and terminating NULL byte
jbe@175 1022 int tabletype = JSON_TABLETYPE_UNKNOWN; // table type: unknown, JSON object, or JSON array
jbe@175 1023 int anyelement = 0; // set to 1 if at least one array element has been processed
jbe@175 1024 size_t keycount = 0; // number of string keys in object
jbe@175 1025 json_key_t *keybuf = NULL; // temporary buffer to store (and sort) string keys of objects
jbe@175 1026 lua_Integer arrayidx; // index to iterate through arrays
jbe@175 1027 // stack shall contain three function arguments:
jbe@164 1028 lua_settop(L, json_export_internal_value_idx);
jbe@175 1029 // if value to encode is the null-marker, then treat it the same as nil:
jbe@164 1030 if (json_isnullmark(L, json_export_internal_value_idx)) {
jbe@164 1031 lua_pop(L, 1);
jbe@157 1032 lua_pushnil(L);
jbe@157 1033 }
jbe@175 1034 // distinguish between different Lua types:
jbe@164 1035 switch (lua_type(L, json_export_internal_value_idx)) {
jbe@175 1036 // value to encode is nil:
jbe@154 1037 case LUA_TNIL:
jbe@175 1038 // return string "null":
jbe@154 1039 lua_pushliteral(L, "null");
jbe@154 1040 return 1;
jbe@175 1041 // value to encode is of type number:
jbe@154 1042 case LUA_TNUMBER:
jbe@175 1043 // convert value to double precision number:
jbe@164 1044 num = lua_tonumber(L, json_export_internal_value_idx);
jbe@175 1045 // throw error if number is not-a-number:
jbe@154 1046 if (isnan(num)) return luaL_error(L, "JSON export not possible for NaN value");
jbe@175 1047 // throw error if number is positive or negative infinity:
jbe@154 1048 if (isinf(num)) return luaL_error(L, "JSON export not possible for infinite numbers");
jbe@175 1049 // return Lua's string encoding of the number:
jbe@164 1050 lua_tostring(L, json_export_internal_value_idx);
jbe@154 1051 return 1;
jbe@175 1052 // value to encode is of type boolean:
jbe@154 1053 case LUA_TBOOLEAN:
jbe@175 1054 // return string "true" or "false" according to boolean value:
jbe@164 1055 if (lua_toboolean(L, json_export_internal_value_idx)) {
jbe@164 1056 lua_pushliteral(L, "true");
jbe@164 1057 } else {
jbe@164 1058 lua_pushliteral(L, "false");
jbe@164 1059 }
jbe@154 1060 return 1;
jbe@175 1061 // value to encode is of type string:
jbe@154 1062 case LUA_TSTRING:
jbe@175 1063 // quote, escape and return string:
jbe@164 1064 str = lua_tolstring(L, 3, &strlen);
jbe@154 1065 luaL_buffinit(L, &buf);
jbe@154 1066 luaL_addchar(&buf, '"');
jbe@154 1067 while (pos < strlen) {
jbe@154 1068 c = str[pos++];
jbe@154 1069 if (c == '"') luaL_addstring(&buf, "\\\"");
jbe@154 1070 else if (c == '\\') luaL_addstring(&buf, "\\\\");
jbe@154 1071 else if (c == 127) luaL_addstring(&buf, "\\u007F");
jbe@154 1072 else if (c >= 32) luaL_addchar(&buf, c);
jbe@154 1073 else if (c == '\b') luaL_addstring(&buf, "\\b");
jbe@154 1074 else if (c == '\f') luaL_addstring(&buf, "\\f");
jbe@154 1075 else if (c == '\n') luaL_addstring(&buf, "\\n");
jbe@154 1076 else if (c == '\r') luaL_addstring(&buf, "\\r");
jbe@154 1077 else if (c == '\t') luaL_addstring(&buf, "\\t");
jbe@154 1078 else if (c == '\v') luaL_addstring(&buf, "\\v");
jbe@154 1079 else {
jbe@154 1080 sprintf(hexcode, "\\u%04X", c);
jbe@154 1081 luaL_addstring(&buf, hexcode);
jbe@154 1082 }
jbe@154 1083 }
jbe@154 1084 luaL_addchar(&buf, '"');
jbe@154 1085 luaL_pushresult(&buf);
jbe@154 1086 return 1;
jbe@175 1087 // value to encode is of type table (this includes JSON objects and JSON arrays):
jbe@154 1088 case LUA_TTABLE:
jbe@175 1089 // use table's metatable to try to determine type of table:
jbe@164 1090 if (lua_getmetatable(L, json_export_internal_value_idx)) {
jbe@154 1091 json_regfetch(L, objectmt);
jbe@154 1092 if (lua_rawequal(L, -2, -1)) {
jbe@154 1093 tabletype = JSON_TABLETYPE_OBJECT;
jbe@154 1094 } else {
jbe@154 1095 json_regfetch(L, arraymt);
jbe@164 1096 if (lua_rawequal(L, -3, -1)) {
jbe@164 1097 tabletype = JSON_TABLETYPE_ARRAY;
jbe@164 1098 } else {
jbe@164 1099 return luaL_error(L, "JSON export not possible for tables with nonsupported metatable");
jbe@164 1100 }
jbe@154 1101 }
jbe@154 1102 }
jbe@175 1103 // replace table with its shadow table if existent, and reset stack:
jbe@154 1104 json_regfetch(L, shadowtbl);
jbe@164 1105 lua_pushvalue(L, json_export_internal_value_idx);
jbe@154 1106 lua_rawget(L, -2);
jbe@164 1107 if (!lua_isnil(L, -1)) lua_replace(L, json_export_internal_value_idx);
jbe@164 1108 lua_settop(L, json_export_internal_value_idx);
jbe@175 1109 // check if type of table is still undetermined:
jbe@154 1110 if (tabletype == JSON_TABLETYPE_UNKNOWN) {
jbe@175 1111 // if yes, iterate over all keys:
jbe@164 1112 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
jbe@164 1113 switch (lua_type(L, -2)) {
jbe@164 1114 case LUA_TSTRING:
jbe@175 1115 // for string keys,
jbe@175 1116 // increase keycount (may avoid another iteration):
jbe@164 1117 keycount++;
jbe@175 1118 // if type of table was unknown, then type of table is a JSON object now:
jbe@164 1119 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_OBJECT;
jbe@175 1120 // if type of table was a JSON array, then the type of table is ambiguous now
jbe@175 1121 // and an error is thrown:
jbe@164 1122 else if (tabletype == JSON_TABLETYPE_ARRAY) goto json_export_tabletype_error;
jbe@164 1123 break;
jbe@164 1124 case LUA_TNUMBER:
jbe@175 1125 // for numeric keys,
jbe@175 1126 // if type of table was unknown, then type of table is a JSON array now:
jbe@164 1127 if (tabletype == JSON_TABLETYPE_UNKNOWN) tabletype = JSON_TABLETYPE_ARRAY;
jbe@175 1128 // if type of table was a JSON object, then the type of table is ambiguous now
jbe@175 1129 // and an error is thrown:
jbe@164 1130 else if (tabletype == JSON_TABLETYPE_OBJECT) goto json_export_tabletype_error;
jbe@164 1131 break;
jbe@154 1132 }
jbe@154 1133 }
jbe@154 1134 }
jbe@175 1135 // set pretty variable to 1 if pretty printing (with indentation) is desired:
jbe@164 1136 pretty = lua_toboolean(L, json_export_internal_indentstring_idx);
jbe@175 1137 // set level variable to corresponding function argument increased by one:
jbe@164 1138 level = lua_tointeger(L, json_export_internal_level_idx) + 1;
jbe@175 1139 // throw error if there are more levels that could be imported by this library:
jbe@164 1140 if (level > JSON_MAXDEPTH) {
jbe@164 1141 return luaL_error(L, "More than %d nested JSON levels", JSON_MAXDEPTH);
jbe@164 1142 }
jbe@175 1143 // distinguish between JSON objects and JSON arrays:
jbe@154 1144 switch (tabletype) {
jbe@175 1145 // JSON object:
jbe@154 1146 case JSON_TABLETYPE_OBJECT:
jbe@175 1147 // calculate count of string keys unless it has been calculated before:
jbe@164 1148 if (!keycount) {
jbe@164 1149 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
jbe@164 1150 if (lua_type(L, -2) == LUA_TSTRING) keycount++;
jbe@164 1151 }
jbe@163 1152 }
jbe@175 1153 // create a sorted list of all string keys in memory:
jbe@163 1154 if (keycount) {
jbe@175 1155 // allocate memory for string keys:
jbe@163 1156 keybuf = calloc(keycount, sizeof(json_key_t));
jbe@175 1157 // check if memory allocation was successful:
jbe@175 1158 if (!keybuf) {
jbe@175 1159 // in case of memory exhaustion, try to collect garbage:
jbe@175 1160 lua_gc(L, LUA_GCCOLLECT, 0);
jbe@175 1161 // try to allocate memory again:
jbe@175 1162 keybuf = calloc(keycount, sizeof(json_key_t));
jbe@175 1163 // throw error if memory allocation failed again:
jbe@175 1164 if (!keybuf) {
jbe@175 1165 return luaL_error(L, "Memory allocation failed in JSON library");
jbe@175 1166 }
jbe@175 1167 }
jbe@175 1168 // copy all string keys to the C array:
jbe@164 1169 for (lua_pushnil(L); lua_next(L, json_export_internal_value_idx); lua_pop(L, 1)) {
jbe@163 1170 if (lua_type(L, -2) == LUA_TSTRING) {
jbe@175 1171 json_key_t *key = keybuf + (pos++);
jbe@163 1172 key->data = lua_tolstring(L, -2, &key->length);
jbe@163 1173 }
jbe@163 1174 }
jbe@175 1175 // sort C array using quicksort:
jbe@163 1176 qsort(keybuf, keycount, sizeof(json_key_t), (void *)json_key_cmp);
jbe@163 1177 }
jbe@175 1178 // create Lua string buffer:
jbe@154 1179 luaL_buffinit(L, &buf);
jbe@175 1180 // add opening bracket to output buffer:
jbe@154 1181 luaL_addchar(&buf, '{');
jbe@175 1182 // iterate through all (sorted) string keys:
jbe@175 1183 for (pos=0; pos<keycount; pos++) {
jbe@175 1184 json_key_t *key = keybuf + pos;
jbe@175 1185 // add comma to output buffer unless we process the first key:
jbe@175 1186 if (pos) luaL_addchar(&buf, ',');
jbe@175 1187 // handle indentation for pretty results:
jbe@164 1188 if (pretty) {
jbe@164 1189 luaL_addchar(&buf, '\n');
jbe@164 1190 for (i=0; i<level; i++) {
jbe@164 1191 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1192 luaL_addvalue(&buf);
jbe@164 1193 }
jbe@164 1194 }
jbe@175 1195 // recursive call to encode key:
jbe@164 1196 lua_pushcfunction(L, json_export_internal);
jbe@164 1197 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1198 lua_pushinteger(L, level);
jbe@163 1199 lua_pushlstring(L, key->data, key->length);
jbe@164 1200 if (lua_pcall(L, 3, 1, 0)) {
jbe@175 1201 // free memory of sorted string keys on error:
jbe@163 1202 if (keybuf) free(keybuf);
jbe@175 1203 // rethrow error:
jbe@163 1204 return lua_error(L);
jbe@154 1205 }
jbe@175 1206 // add encoded key to output buffer:
jbe@163 1207 luaL_addvalue(&buf);
jbe@175 1208 // add colon to output buffer:
jbe@163 1209 luaL_addchar(&buf, ':');
jbe@175 1210 // handle indentation for pretty results:
jbe@164 1211 if (pretty) luaL_addchar(&buf, ' ');
jbe@175 1212 // recursive call to encode value:
jbe@164 1213 lua_pushcfunction(L, json_export_internal);
jbe@164 1214 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1215 lua_pushinteger(L, level);
jbe@163 1216 lua_pushlstring(L, key->data, key->length);
jbe@164 1217 lua_rawget(L, json_export_internal_value_idx);
jbe@164 1218 if (lua_pcall(L, 3, 1, 0)) {
jbe@175 1219 // free memory of sorted string keys on error:
jbe@163 1220 if (keybuf) free(keybuf);
jbe@175 1221 // rethrow error:
jbe@163 1222 return lua_error(L);
jbe@163 1223 }
jbe@175 1224 // add encoded value to output buffer:
jbe@163 1225 luaL_addvalue(&buf);
jbe@154 1226 }
jbe@175 1227 // decrement level variable for all following statements:
jbe@175 1228 level--;
jbe@175 1229 // free memory of sorted string keys:
jbe@163 1230 if (keybuf) free(keybuf);
jbe@175 1231 // handle indentation for pretty results:
jbe@164 1232 if (pretty && keycount != 0) {
jbe@164 1233 luaL_addchar(&buf, '\n');
jbe@175 1234 for (i=0; i<level; i++) {
jbe@164 1235 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1236 luaL_addvalue(&buf);
jbe@164 1237 }
jbe@164 1238 }
jbe@175 1239 // add closing bracket to output buffer:
jbe@154 1240 luaL_addchar(&buf, '}');
jbe@175 1241 // for pretty results, add final newline character if outermost container is processed:
jbe@175 1242 if (pretty && level == 0) luaL_addchar(&buf, '\n');
jbe@175 1243 // convert and return buffer:
jbe@154 1244 luaL_pushresult(&buf);
jbe@154 1245 return 1;
jbe@175 1246 // JSON array:
jbe@154 1247 case JSON_TABLETYPE_ARRAY:
jbe@175 1248 // reserve an extra element on the stack (needed because Lua buffer has unknown size on stack):
jbe@164 1249 lua_settop(L, json_export_internal_tmp_idx);
jbe@175 1250 // create Lua string buffer:
jbe@154 1251 luaL_buffinit(L, &buf);
jbe@175 1252 // add opening bracket to output buffer:
jbe@154 1253 luaL_addchar(&buf, '[');
jbe@175 1254 // iterate through integer keys:
jbe@175 1255 for (arrayidx = 1; ; arrayidx++) {
jbe@175 1256 // get value in array, and break if nil:
jbe@175 1257 lua_rawgeti(L, json_export_internal_value_idx, arrayidx);
jbe@154 1258 if (lua_isnil(L, -1)) {
jbe@154 1259 lua_pop(L, 1);
jbe@154 1260 break;
jbe@154 1261 }
jbe@175 1262 // store value below Lua string buffer on stack (to allow operation on string buffer):
jbe@164 1263 lua_replace(L, json_export_internal_tmp_idx);
jbe@175 1264 //
jbe@175 1265 // add comma to output buffer unless we process the first element:
jbe@164 1266 if (anyelement) luaL_addchar(&buf, ',');
jbe@175 1267 // remember that we processed an element:
jbe@164 1268 anyelement = 1;
jbe@175 1269 // handle indentation for pretty results:
jbe@164 1270 if (pretty) {
jbe@164 1271 luaL_addchar(&buf, '\n');
jbe@164 1272 for (i=0; i<level; i++) {
jbe@164 1273 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1274 luaL_addvalue(&buf);
jbe@164 1275 }
jbe@164 1276 }
jbe@175 1277 // recursive call to encode previously stored value:
jbe@164 1278 lua_pushcfunction(L, json_export_internal);
jbe@164 1279 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1280 lua_pushinteger(L, level);
jbe@164 1281 lua_pushvalue(L, json_export_internal_tmp_idx);
jbe@164 1282 lua_call(L, 3, 1);
jbe@175 1283 // add encoded value to output buffer:
jbe@154 1284 luaL_addvalue(&buf);
jbe@154 1285 }
jbe@175 1286 // decrement level variable for all following statements:
jbe@175 1287 level--;
jbe@175 1288 // handle indentation for pretty results:
jbe@164 1289 if (pretty && anyelement) {
jbe@164 1290 luaL_addchar(&buf, '\n');
jbe@175 1291 for (i=0; i<level; i++) {
jbe@164 1292 lua_pushvalue(L, json_export_internal_indentstring_idx);
jbe@164 1293 luaL_addvalue(&buf);
jbe@164 1294 }
jbe@164 1295 }
jbe@175 1296 // add closing bracket to output buffer:
jbe@154 1297 luaL_addchar(&buf, ']');
jbe@175 1298 // for pretty results, add final newline character if outermost container is processed:
jbe@175 1299 if (pretty && level == 0) luaL_addchar(&buf, '\n');
jbe@175 1300 // convert and return buffer:
jbe@154 1301 luaL_pushresult(&buf);
jbe@154 1302 return 1;
jbe@154 1303 }
jbe@175 1304 // throw error if table type is unknown:
jbe@154 1305 json_export_tabletype_error:
jbe@154 1306 return luaL_error(L, "JSON export not possible for ambiguous table (cannot decide whether it is an object or array)");
jbe@154 1307 }
jbe@175 1308 // all other datatypes are considered an error:
jbe@166 1309 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 1310 }
jbe@154 1311
jbe@175 1312 // encodes a JSON document (passed as argument):
jbe@164 1313 static int json_export(lua_State *L) {
jbe@175 1314 // stack shall contain one function argument:
jbe@164 1315 lua_settop(L, 1);
jbe@175 1316 // call json_export_internal function with proper arguments:
jbe@164 1317 lua_pushcfunction(L, json_export_internal);
jbe@164 1318 lua_pushnil(L);
jbe@164 1319 lua_pushinteger(L, 0);
jbe@164 1320 lua_pushvalue(L, 1);
jbe@164 1321 lua_call(L, 3, 1);
jbe@175 1322 // return result:
jbe@164 1323 return 1;
jbe@164 1324 }
jbe@164 1325
jbe@175 1326 // encodes a JSON document (passed as first argument)
jbe@175 1327 // with indentation (indentation string may be passed as second argument):
jbe@164 1328 static int json_pretty(lua_State *L) {
jbe@175 1329 // stack shall contain two function arguments:
jbe@164 1330 lua_settop(L, 2);
jbe@175 1331 // call json_export_internal function with proper arguments:
jbe@164 1332 lua_pushcfunction(L, json_export_internal);
jbe@164 1333 if (lua_isnil(L, 2)) lua_pushliteral(L, " ");
jbe@164 1334 else lua_pushvalue(L, 2);
jbe@164 1335 lua_pushinteger(L, 0);
jbe@164 1336 lua_pushvalue(L, 1);
jbe@164 1337 lua_call(L, 3, 1);
jbe@175 1338 // return result:
jbe@164 1339 return 1;
jbe@164 1340 }
jbe@164 1341
jbe@149 1342 // functions in library module:
jbe@121 1343 static const struct luaL_Reg json_module_functions[] = {
jbe@133 1344 {"object", json_object},
jbe@173 1345 {"array", json_array},
jbe@121 1346 {"import", json_import},
jbe@154 1347 {"export", json_export},
jbe@164 1348 {"pretty", json_pretty},
jbe@173 1349 {"get", json_get},
jbe@173 1350 {"type", json_type},
jbe@173 1351 {"set", json_set},
jbe@121 1352 {NULL, NULL}
jbe@121 1353 };
jbe@121 1354
jbe@149 1355 // metamethods for JSON objects, JSON arrays, and unknown JSON collections (object or array):
jbe@126 1356 static const struct luaL_Reg json_metatable_functions[] = {
jbe@130 1357 {"__len", json_len},
jbe@130 1358 {"__index", json_index},
jbe@130 1359 {"__newindex", json_newindex},
jbe@135 1360 {"__pairs", json_pairs},
jbe@134 1361 {"__ipairs", json_ipairs},
jbe@160 1362 {"__tostring", json_export},
jbe@126 1363 {NULL, NULL}
jbe@126 1364 };
jbe@126 1365
jbe@157 1366 // metamethods for JSON null marker:
jbe@157 1367 static const struct luaL_Reg json_nullmark_metamethods[] = {
jbe@157 1368 {"__tostring", json_nullmark_tostring},
jbe@157 1369 {NULL, NULL}
jbe@157 1370 };
jbe@157 1371
jbe@149 1372 // initializes json library:
jbe@121 1373 int luaopen_json(lua_State *L) {
jbe@149 1374 // empty stack:
jbe@126 1375 lua_settop(L, 0);
jbe@149 1376 // push library module onto stack position 1:
jbe@149 1377 lua_newtable(L);
jbe@149 1378 // register library functions:
jbe@149 1379 luaL_setfuncs(L, json_module_functions, 0);
jbe@149 1380 // create and store objectmt:
jbe@138 1381 lua_newtable(L);
jbe@138 1382 luaL_setfuncs(L, json_metatable_functions, 0);
jbe@144 1383 json_regstore(L, objectmt);
jbe@149 1384 // create and store arraymt:
jbe@138 1385 lua_newtable(L);
jbe@138 1386 luaL_setfuncs(L, json_metatable_functions, 0);
jbe@144 1387 json_regstore(L, arraymt);
jbe@149 1388 // create and store ephemeron table to store shadow tables for each JSON object/array
jbe@149 1389 // to allow NULL values returned as nil
jbe@149 1390 lua_newtable(L);
jbe@138 1391 lua_newtable(L); // metatable for ephemeron table
jbe@121 1392 lua_pushliteral(L, "__mode");
jbe@121 1393 lua_pushliteral(L, "k");
jbe@138 1394 lua_rawset(L, -3);
jbe@138 1395 lua_setmetatable(L, -2);
jbe@144 1396 json_regstore(L, shadowtbl);
jbe@157 1397 // set metatable of null marker and make it available through library module:
jbe@157 1398 json_pushnullmark(L);
jbe@157 1399 lua_newtable(L);
jbe@157 1400 luaL_setfuncs(L, json_nullmark_metamethods, 0);
jbe@157 1401 lua_setmetatable(L, -2);
jbe@157 1402 lua_setfield(L, 1, "null");
jbe@157 1403 // return library module (that's expected on top of stack):
jbe@121 1404 return 1;
jbe@121 1405 }

Impressum / About Us