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