neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

lua_cjson.c (63516B)


      1 // Upstream: https://github.com/openresty/lua-cjson/blob/master/lua_cjson.c
      2 // Synced Commit; 91ca29db9a4a4fd0eedaebcd5d5f3ba2ace5ae63
      3 
      4 /* Lua CJSON - JSON support for Lua
      5 *
      6 * Copyright (c) 2010-2012  Mark Pulford <mark@kyne.com.au>
      7 *
      8 * Permission is hereby granted, free of charge, to any person obtaining
      9 * a copy of this software and associated documentation files (the
     10 * "Software"), to deal in the Software without restriction, including
     11 * without limitation the rights to use, copy, modify, merge, publish,
     12 * distribute, sublicense, and/or sell copies of the Software, and to
     13 * permit persons to whom the Software is furnished to do so, subject to
     14 * the following conditions:
     15 *
     16 * The above copyright notice and this permission notice shall be
     17 * included in all copies or substantial portions of the Software.
     18 *
     19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     20 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     21 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
     22 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
     23 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
     24 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
     25 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     26 */
     27 
     28 /* Caveats:
     29 * - JSON "null" values are represented as lightuserdata since Lua
     30 *   tables cannot contain "nil". Compare with cjson.null.
     31 * - Invalid UTF-8 characters are not detected and will be passed
     32 *   untouched. If required, UTF-8 error checking should be done
     33 *   outside this library.
     34 * - Javascript comments are not part of the JSON spec, and are not
     35 *   currently supported.
     36 *
     37 * Note: Decoding is slower than encoding. Lua spends significant
     38 *       time (30%) managing tables when parsing JSON since it is
     39 *       difficult to know object/array sizes ahead of time.
     40 */
     41 
     42 #include <assert.h>
     43 #include <stdint.h>
     44 #include <string.h>
     45 #include <math.h>
     46 // #include <stdint.h>
     47 #include <limits.h>
     48 #include <lua.h>
     49 #include <lauxlib.h>
     50 
     51 #include "nvim/lua/executor.h"
     52 
     53 #include "lua_cjson.h"
     54 #include "strbuf.h"
     55 #include "fpconv.h"
     56 
     57 #ifndef CJSON_MODNAME
     58 #define CJSON_MODNAME   "cjson"
     59 #endif
     60 
     61 #ifndef CJSON_VERSION
     62 #define CJSON_VERSION   "2.1.0.11"
     63 #endif
     64 
     65 #ifdef _MSC_VER
     66 // #define CJSON_EXPORT    __declspec(dllexport)
     67 // #define strncasecmp(x,y,z) _strnicmp(x,y,z)
     68 #else
     69 #define CJSON_EXPORT    extern
     70 #endif
     71 
     72 /* Workaround for Solaris platforms missing isinf() */
     73 #if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
     74 #define isinf(x) (!isnan(x) && isnan((x) - (x)))
     75 #endif
     76 
     77 #define DEFAULT_SPARSE_CONVERT 0
     78 #define DEFAULT_SPARSE_RATIO 2
     79 #define DEFAULT_SPARSE_SAFE 10
     80 #define DEFAULT_ENCODE_MAX_DEPTH 1000
     81 #define DEFAULT_DECODE_MAX_DEPTH 1000
     82 #define DEFAULT_ENCODE_INVALID_NUMBERS 0
     83 #define DEFAULT_DECODE_INVALID_NUMBERS 1
     84 #define DEFAULT_ENCODE_KEEP_BUFFER 1
     85 #define DEFAULT_ENCODE_NUMBER_PRECISION 16
     86 #define DEFAULT_ENCODE_EMPTY_TABLE_AS_OBJECT 0
     87 #define DEFAULT_DECODE_ARRAY_WITH_ARRAY_MT 0
     88 #define DEFAULT_DECODE_SKIP_COMMENTS 0
     89 #define DEFAULT_ENCODE_ESCAPE_FORWARD_SLASH 1
     90 #define DEFAULT_ENCODE_SKIP_UNSUPPORTED_VALUE_TYPES 0
     91 #define DEFAULT_ENCODE_INDENT NULL
     92 #define DEFAULT_ENCODE_SORT_KEYS 0
     93 
     94 #ifdef DISABLE_INVALID_NUMBERS
     95 #undef DEFAULT_DECODE_INVALID_NUMBERS
     96 #define DEFAULT_DECODE_INVALID_NUMBERS 0
     97 #endif
     98 
     99 #ifdef _MSC_VER
    100 /* Microsoft C compiler lacks strncasecmp and strcasecmp. */
    101 #define strncasecmp _strnicmp
    102 #define strcasecmp _stricmp
    103 #endif
    104 
    105 #if LONG_MAX > ((1UL << 31) - 1)
    106 #define json_lightudata_mask(ludata)                                         \
    107    ((void *) ((uintptr_t) (ludata) & ((1UL << 47) - 1)))
    108 
    109 #else
    110 #define json_lightudata_mask(ludata)    (ludata)
    111 #endif
    112 
    113 #if LUA_VERSION_NUM >= 502
    114 #define lua_objlen(L,i)		luaL_len(L, (i))
    115 #endif
    116 
    117 static const char * const *json_empty_array;
    118 static const char * const *json_array;
    119 
    120 typedef enum {
    121    T_OBJ_BEGIN,
    122    T_OBJ_END,
    123    T_ARR_BEGIN,
    124    T_ARR_END,
    125    T_STRING,
    126    T_NUMBER,
    127    T_INTEGER,
    128    T_BOOLEAN,
    129    T_NULL,
    130    T_COLON,
    131    T_COMMA,
    132    T_END,
    133    T_WHITESPACE,
    134    T_ERROR,
    135    T_UNKNOWN
    136 } json_token_type_t;
    137 
    138 static const char *json_token_type_name[] = {
    139    "T_OBJ_BEGIN",
    140    "T_OBJ_END",
    141    "T_ARR_BEGIN",
    142    "T_ARR_END",
    143    "T_STRING",
    144    "T_NUMBER",
    145    "T_INTEGER",
    146    "T_BOOLEAN",
    147    "T_NULL",
    148    "T_COLON",
    149    "T_COMMA",
    150    "T_END",
    151    "T_WHITESPACE",
    152    "T_ERROR",
    153    "T_UNKNOWN",
    154    NULL
    155 };
    156 
    157 typedef struct {
    158    strbuf_t *buf;
    159    size_t offset;
    160    size_t length;
    161    int raw_typ;
    162    union {
    163        lua_Number number;
    164        const char *string;
    165    } raw;
    166 } key_entry_t;
    167 
    168 /* Stores all keys for a table when key sorting is enabled.
    169 * - buf: buffer holding serialized key strings
    170 * - keys: array of key_entry_t pointing into buf
    171 * - size: number of keys stored
    172 * - capacity: allocated capacity of keys array
    173 */
    174 typedef struct {
    175    strbuf_t buf;
    176    key_entry_t *keys;
    177    size_t size;
    178    size_t capacity;
    179 } keybuf_t;
    180 
    181 #define KEYBUF_DEFAULT_CAPACITY 32
    182 
    183 typedef struct {
    184    json_token_type_t ch2token[256];
    185    char escape2char[256];  /* Decoding */
    186 
    187    /* encode_buf is only allocated and used when
    188     * encode_keep_buffer is set */
    189    strbuf_t encode_buf;
    190 
    191    /* encode_keybuf is only allocated and used when
    192     * sort_keys is set */
    193    keybuf_t encode_keybuf;
    194 
    195    int encode_sparse_convert;
    196    int encode_sparse_ratio;
    197    int encode_sparse_safe;
    198    int encode_max_depth;
    199    int encode_invalid_numbers;     /* 2 => Encode as "null" */
    200    int encode_number_precision;
    201    int encode_keep_buffer;
    202    int encode_empty_table_as_object;
    203    int encode_escape_forward_slash;
    204    const char *encode_indent;
    205    int encode_sort_keys;
    206 
    207    int decode_invalid_numbers;
    208    int decode_max_depth;
    209    int decode_array_with_array_mt;
    210    int decode_skip_comments;
    211    int encode_skip_unsupported_value_types;
    212 } json_config_t;
    213 
    214 typedef struct {
    215    const char **char2escape[256];
    216    const char *indent;
    217    int sort_keys;
    218 
    219    /* keybuf is only allocated and used when
    220     * sort_keys is set */
    221    keybuf_t keybuf;
    222 } json_encode_options_t;
    223 
    224 typedef struct {
    225    json_config_t *cfg;
    226    json_encode_options_t *options;
    227    strbuf_t *json;
    228 } json_encode_t;
    229 
    230 typedef struct {
    231    /* convert null in json objects to lua nil instead of vim.NIL */
    232    bool luanil_object;
    233    /* convert null in json arrays to lua nil instead of vim.NIL */
    234    bool luanil_array;
    235    bool skip_comments;
    236 } json_options_t;
    237 
    238 typedef struct {
    239    const char *data;
    240    const char *ptr;
    241    strbuf_t *tmp;    /* Temporary storage for strings */
    242    json_config_t *cfg;
    243    json_options_t *options;
    244    int current_depth;
    245 } json_parse_t;
    246 
    247 typedef struct {
    248    json_token_type_t type;
    249    size_t index;
    250    union {
    251        const char *string;
    252        double number;
    253        lua_Integer integer;
    254        int boolean;
    255    } value;
    256    size_t string_len;
    257 } json_token_t;
    258 
    259 static const char *char2escape[256] = {
    260    "\\u0000", "\\u0001", "\\u0002", "\\u0003",
    261    "\\u0004", "\\u0005", "\\u0006", "\\u0007",
    262    "\\b", "\\t", "\\n", "\\u000b",
    263    "\\f", "\\r", "\\u000e", "\\u000f",
    264    "\\u0010", "\\u0011", "\\u0012", "\\u0013",
    265    "\\u0014", "\\u0015", "\\u0016", "\\u0017",
    266    "\\u0018", "\\u0019", "\\u001a", "\\u001b",
    267    "\\u001c", "\\u001d", "\\u001e", "\\u001f",
    268    NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
    269    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    270    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    271    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    272    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    273    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    274    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    275    NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
    276    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    277    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    278    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    279    NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
    280    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    281    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    282    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    283    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    284    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    285    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    286    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    287    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    288    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    289    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    290    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    291    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    292    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    293    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    294    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    295    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    296 };
    297 
    298 /* ===== CONFIGURATION ===== */
    299 
    300 static json_config_t *json_fetch_config(lua_State *l)
    301 {
    302    json_config_t *cfg;
    303 
    304    cfg = (json_config_t *)lua_touserdata(l, lua_upvalueindex(1));
    305    if (!cfg)
    306        luaL_error(l, "BUG: Unable to fetch CJSON configuration");
    307 
    308    return cfg;
    309 }
    310 
    311 /* Ensure the correct number of arguments have been provided.
    312 * Pad with nil to allow other functions to simply check arg[i]
    313 * to find whether an argument was provided */
    314 /*
    315 static json_config_t *json_arg_init(lua_State *l, int args)
    316 {
    317    luaL_argcheck(l, lua_gettop(l) <= args, args + 1,
    318                  "found too many arguments");
    319 
    320    while (lua_gettop(l) < args)
    321        lua_pushnil(l);
    322 
    323    return json_fetch_config(l);
    324 }
    325 */
    326 
    327 /* Process integer options for configuration functions */
    328 /*
    329 static int json_integer_option(lua_State *l, int optindex, int *setting,
    330                               int min, int max)
    331 {
    332    char errmsg[64];
    333    int value;
    334 
    335    if (!lua_isnil(l, optindex)) {
    336        value = luaL_checkinteger(l, optindex);
    337        snprintf(errmsg, sizeof(errmsg), "expected integer between %d and %d", min, max);
    338        luaL_argcheck(l, min <= value && value <= max, 1, errmsg);
    339        *setting = value;
    340    }
    341 
    342    lua_pushinteger(l, *setting);
    343 
    344    return 1;
    345 }
    346 */
    347 
    348 /* Process enumerated arguments for a configuration function */
    349 /*
    350 static int json_enum_option(lua_State *l, int optindex, int *setting,
    351                            const char **options, int bool_true)
    352 {
    353    static const char *bool_options[] = { "off", "on", NULL };
    354 
    355    if (!options) {
    356        options = bool_options;
    357        bool_true = 1;
    358    }
    359 
    360    if (!lua_isnil(l, optindex)) {
    361        if (bool_true && lua_isboolean(l, optindex))
    362            *setting = lua_toboolean(l, optindex) * bool_true;
    363        else
    364            *setting = luaL_checkoption(l, optindex, NULL, options);
    365    }
    366 
    367    if (bool_true && (*setting == 0 || *setting == bool_true))
    368        lua_pushboolean(l, *setting);
    369    else
    370        lua_pushstring(l, options[*setting]);
    371 
    372    return 1;
    373 }
    374 */
    375 
    376 /* Process string option for a configuration function */
    377 /*
    378 static int json_string_option(lua_State *l, int optindex, const char **setting)
    379 {
    380    if (!lua_isnil(l, optindex)) {
    381        const char *value = luaL_checkstring(l, optindex);
    382        *setting = value;
    383    }
    384 
    385    lua_pushstring(l, *setting ? *setting : "");
    386    return 1;
    387 }
    388 */
    389 
    390 /* Configures handling of extremely sparse arrays:
    391 * convert: Convert extremely sparse arrays into objects? Otherwise error.
    392 * ratio: 0: always allow sparse; 1: never allow sparse; >1: use ratio
    393 * safe: Always use an array when the max index <= safe */
    394 /*
    395 static int json_cfg_encode_sparse_array(lua_State *l)
    396 {
    397    json_config_t *cfg = json_arg_init(l, 3);
    398 
    399    json_enum_option(l, 1, &cfg->encode_sparse_convert, NULL, 1);
    400    json_integer_option(l, 2, &cfg->encode_sparse_ratio, 0, INT_MAX);
    401    json_integer_option(l, 3, &cfg->encode_sparse_safe, 0, INT_MAX);
    402 
    403    return 3;
    404 }
    405 */
    406 
    407 /* Configures the maximum number of nested arrays/objects allowed when
    408 * encoding */
    409 /*
    410 static int json_cfg_encode_max_depth(lua_State *l)
    411 {
    412    json_config_t *cfg = json_arg_init(l, 1);
    413 
    414    return json_integer_option(l, 1, &cfg->encode_max_depth, 1, INT_MAX);
    415 }
    416 */
    417 
    418 /* Configures the maximum number of nested arrays/objects allowed when
    419 * encoding */
    420 /*
    421 static int json_cfg_decode_max_depth(lua_State *l)
    422 {
    423    json_config_t *cfg = json_arg_init(l, 1);
    424 
    425    return json_integer_option(l, 1, &cfg->decode_max_depth, 1, INT_MAX);
    426 }
    427 */
    428 
    429 /* Configures number precision when converting doubles to text */
    430 /*
    431 static int json_cfg_encode_number_precision(lua_State *l)
    432 {
    433    json_config_t *cfg = json_arg_init(l, 1);
    434 
    435    return json_integer_option(l, 1, &cfg->encode_number_precision, 1, 16);
    436 }
    437 */
    438 
    439 /* Configures how to treat empty table when encode lua table */
    440 /*
    441 static int json_cfg_encode_empty_table_as_object(lua_State *l)
    442 {
    443    json_config_t *cfg = json_arg_init(l, 1);
    444 
    445    return json_enum_option(l, 1, &cfg->encode_empty_table_as_object, NULL, 1);
    446 }
    447 */
    448 
    449 /* Configures how to decode arrays */
    450 /*
    451 static int json_cfg_decode_array_with_array_mt(lua_State *l)
    452 {
    453    json_config_t *cfg = json_arg_init(l, 1);
    454 
    455    json_enum_option(l, 1, &cfg->decode_array_with_array_mt, NULL, 1);
    456 
    457    return 1;
    458 }
    459 */
    460 
    461 /* Configures whether decoder should skip comments */
    462 /*
    463 static int json_cfg_decode_skip_comments(lua_State *l)
    464 {
    465    json_config_t *cfg = json_arg_init(l, 1);
    466 
    467    json_enum_option(l, 1, &cfg->decode_skip_comments, NULL, 1);
    468 
    469    return 1;
    470 }
    471 */
    472 
    473 /* Configure how to treat invalid types */
    474 /*
    475 static int json_cfg_encode_skip_unsupported_value_types(lua_State *l)
    476 {
    477    json_config_t *cfg = json_arg_init(l, 1);
    478 
    479    json_enum_option(l, 1, &cfg->encode_skip_unsupported_value_types, NULL, 1);
    480 
    481    return 1;
    482 }
    483 */
    484 
    485 /* Configures JSON encoding buffer persistence */
    486 /*
    487 static int json_cfg_encode_keep_buffer(lua_State *l)
    488 {
    489    json_config_t *cfg = json_arg_init(l, 1);
    490    int old_value;
    491 
    492    old_value = cfg->encode_keep_buffer;
    493 
    494    json_enum_option(l, 1, &cfg->encode_keep_buffer, NULL, 1);
    495 
    496    // Init / free the buffer if the setting has changed
    497    if (old_value ^ cfg->encode_keep_buffer) {
    498        if (cfg->encode_keep_buffer)
    499            strbuf_init(&cfg->encode_buf, 0);
    500        else
    501            strbuf_free(&cfg->encode_buf);
    502    }
    503 
    504    return 1;
    505 }
    506 */
    507 
    508 /* Configure how to indent output */
    509 /*
    510 static int json_cfg_encode_indent(lua_State *l)
    511 {
    512    json_config_t *cfg = json_arg_init(l, 1);
    513 
    514    json_string_option(l, 1, &cfg->encode_indent);
    515    // simplify further checking
    516    if (cfg->encode_indent[0] == '\0') cfg->encode_indent = NULL;
    517 
    518    return 1;
    519 }
    520 */
    521 
    522 #if defined(DISABLE_INVALID_NUMBERS) && !defined(USE_INTERNAL_FPCONV)
    523 void json_verify_invalid_number_setting(lua_State *l, int *setting)
    524 {
    525    if (*setting == 1) {
    526        *setting = 0;
    527        luaL_error(l, "Infinity, NaN, and/or hexadecimal numbers are not supported.");
    528    }
    529 }
    530 #else
    531 #define json_verify_invalid_number_setting(l, s)    do { } while(0)
    532 #endif
    533 
    534 /*
    535 static int json_cfg_encode_invalid_numbers(lua_State *l)
    536 {
    537    static const char *options[] = { "off", "on", "null", NULL };
    538    json_config_t *cfg = json_arg_init(l, 1);
    539 
    540    json_enum_option(l, 1, &cfg->encode_invalid_numbers, options, 1);
    541 
    542    json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
    543 
    544    return 1;
    545 }
    546 */
    547 
    548 /*
    549 static int json_cfg_decode_invalid_numbers(lua_State *l)
    550 {
    551    json_config_t *cfg = json_arg_init(l, 1);
    552 
    553    json_enum_option(l, 1, &cfg->decode_invalid_numbers, NULL, 1);
    554 
    555    json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers);
    556 
    557    return 1;
    558 }
    559 */
    560 
    561 /*
    562 static int json_cfg_encode_escape_forward_slash(lua_State *l)
    563 {
    564    int            ret;
    565    json_config_t *cfg = json_arg_init(l, 1);
    566 
    567    ret = json_enum_option(l, 1, &cfg->encode_escape_forward_slash, NULL, 1);
    568    if (cfg->encode_escape_forward_slash) {
    569        char2escape['/'] = "\\/";
    570    } else {
    571        char2escape['/'] = NULL;
    572    }
    573    return ret;
    574 }
    575 */
    576 
    577 /*
    578 static int json_cfg_encode_sort_keys(lua_State *l)
    579 {
    580    json_config_t *cfg = json_arg_init(l, 1);
    581 
    582    json_enum_option(l, 1, &cfg->encode_sort_keys, NULL, 1);
    583 
    584    return 1;
    585 }
    586 */
    587 
    588 static int json_destroy_config(lua_State *l)
    589 {
    590    json_config_t *cfg;
    591 
    592    cfg = (json_config_t *)lua_touserdata(l, 1);
    593    if (cfg)
    594        strbuf_free(&cfg->encode_buf);
    595    cfg = NULL;
    596 
    597    return 0;
    598 }
    599 
    600 static void json_create_config(lua_State *l)
    601 {
    602    json_config_t *cfg;
    603    int i;
    604 
    605    cfg = (json_config_t *)lua_newuserdata(l, sizeof(*cfg));
    606    if (!cfg)
    607        abort();
    608 
    609    memset(cfg, 0, sizeof(*cfg));
    610 
    611    /* Create GC method to clean up strbuf */
    612    lua_newtable(l);
    613    lua_pushcfunction(l, json_destroy_config);
    614    lua_setfield(l, -2, "__gc");
    615    lua_setmetatable(l, -2);
    616 
    617    cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
    618    cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
    619    cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
    620    cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
    621    cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
    622    cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
    623    cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
    624    cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
    625    cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;
    626    cfg->encode_empty_table_as_object = DEFAULT_ENCODE_EMPTY_TABLE_AS_OBJECT;
    627    cfg->decode_array_with_array_mt = DEFAULT_DECODE_ARRAY_WITH_ARRAY_MT;
    628    cfg->decode_skip_comments = DEFAULT_DECODE_SKIP_COMMENTS;
    629    cfg->encode_escape_forward_slash = DEFAULT_ENCODE_ESCAPE_FORWARD_SLASH;
    630    cfg->encode_skip_unsupported_value_types = DEFAULT_ENCODE_SKIP_UNSUPPORTED_VALUE_TYPES;
    631    cfg->encode_indent = DEFAULT_ENCODE_INDENT;
    632    cfg->encode_sort_keys = DEFAULT_ENCODE_SORT_KEYS;
    633 
    634 #if DEFAULT_ENCODE_KEEP_BUFFER > 0
    635    strbuf_init(&cfg->encode_buf, 0);
    636 #endif
    637 
    638    /* Decoding init */
    639 
    640    /* Tag all characters as an error */
    641    for (i = 0; i < 256; i++)
    642        cfg->ch2token[i] = T_ERROR;
    643 
    644    /* Set tokens that require no further processing */
    645    cfg->ch2token['{'] = T_OBJ_BEGIN;
    646    cfg->ch2token['}'] = T_OBJ_END;
    647    cfg->ch2token['['] = T_ARR_BEGIN;
    648    cfg->ch2token[']'] = T_ARR_END;
    649    cfg->ch2token[','] = T_COMMA;
    650    cfg->ch2token[':'] = T_COLON;
    651    cfg->ch2token['\0'] = T_END;
    652    cfg->ch2token[' '] = T_WHITESPACE;
    653    cfg->ch2token['\t'] = T_WHITESPACE;
    654    cfg->ch2token['\n'] = T_WHITESPACE;
    655    cfg->ch2token['\r'] = T_WHITESPACE;
    656 
    657    /* Update characters that require further processing */
    658    cfg->ch2token['f'] = T_UNKNOWN;     /* false? */
    659    cfg->ch2token['i'] = T_UNKNOWN;     /* inf, infinity? */
    660    cfg->ch2token['I'] = T_UNKNOWN;
    661    cfg->ch2token['n'] = T_UNKNOWN;     /* null, nan? */
    662    cfg->ch2token['N'] = T_UNKNOWN;
    663    cfg->ch2token['t'] = T_UNKNOWN;     /* true? */
    664    cfg->ch2token['"'] = T_UNKNOWN;     /* string? */
    665    cfg->ch2token['+'] = T_UNKNOWN;     /* number? */
    666    cfg->ch2token['-'] = T_UNKNOWN;
    667    for (i = 0; i < 10; i++)
    668        cfg->ch2token['0' + i] = T_UNKNOWN;
    669 
    670    /* Lookup table for parsing escape characters */
    671    for (i = 0; i < 256; i++)
    672        cfg->escape2char[i] = 0;          /* String error */
    673    cfg->escape2char['"'] = '"';
    674    cfg->escape2char['\\'] = '\\';
    675    cfg->escape2char['/'] = '/';
    676    cfg->escape2char['b'] = '\b';
    677    cfg->escape2char['t'] = '\t';
    678    cfg->escape2char['n'] = '\n';
    679    cfg->escape2char['f'] = '\f';
    680    cfg->escape2char['r'] = '\r';
    681    cfg->escape2char['u'] = 'u';          /* Unicode parsing required */
    682 }
    683 
    684 /* ===== ENCODING ===== */
    685 
    686 static void json_encode_exception(lua_State *l, json_encode_t *ctx, int lindex,
    687                                  const char *reason)
    688 {
    689    if (!ctx->cfg->encode_keep_buffer)
    690        strbuf_free(ctx->json);
    691 
    692    if (ctx->options->sort_keys) {
    693        strbuf_free(&ctx->options->keybuf.buf);
    694        free(ctx->options->keybuf.keys);
    695    }
    696 
    697    luaL_error(l, "Cannot serialise %s: %s",
    698                  lua_typename(l, lua_type(l, lindex)), reason);
    699 }
    700 
    701 static void json_append_string_contents(lua_State *l, json_encode_t *ctx,
    702                                        int lindex, int use_keybuf)
    703 {
    704    const char *escstr;
    705    const char *str;
    706    size_t len;
    707    size_t i;
    708    strbuf_t *json = ctx->json;
    709    if (use_keybuf) {
    710        json = &ctx->options->keybuf.buf;
    711    }
    712 
    713    str = lua_tolstring(l, lindex, &len);
    714 
    715    /* Worst case is len * 6 (all unicode escapes).
    716     * This buffer is reused constantly for small strings
    717     * If there are any excess pages, they won't be hit anyway.
    718     * This gains ~5% speedup. */
    719    if (len >= SIZE_MAX / 6)
    720        abort(); /* Overflow check */
    721    strbuf_ensure_empty_length(json, len * 6);
    722 
    723    for (i = 0; i < len; i++) {
    724        escstr = (*ctx->options->char2escape)[(unsigned char)str[i]];
    725        if (escstr)
    726            strbuf_append_string(json, escstr);
    727        else
    728            strbuf_append_char_unsafe(json, str[i]);
    729    }
    730 }
    731 
    732 /* json_append_string args:
    733 * - lua_State
    734 * - JSON encode ctx
    735 * - String (Lua stack index)
    736 *
    737 * Returns nothing. Doesn't remove string from Lua stack */
    738 static void json_append_string(lua_State *l, json_encode_t *ctx, int lindex)
    739 {
    740    strbuf_append_char(ctx->json, '\"');
    741    json_append_string_contents(l, ctx, lindex, false);
    742    strbuf_append_char(ctx->json, '\"');
    743 }
    744 
    745 /* Find the size of the array on the top of the Lua stack
    746 * -1   object (not a pure array)
    747 * >=0  elements in array
    748 */
    749 static int lua_array_length(lua_State *l, json_encode_t *ctx)
    750 {
    751    double k;
    752    int max;
    753    int items;
    754    json_config_t *cfg = ctx->cfg;
    755 
    756    max = 0;
    757    items = 0;
    758 
    759    lua_pushnil(l);
    760    /* table, startkey */
    761    while (lua_next(l, -2) != 0) {
    762        /* table, key, value */
    763        if (lua_type(l, -2) == LUA_TNUMBER &&
    764            (k = lua_tonumber(l, -2))) {
    765            /* Integer >= 1 ? */
    766            if (floor(k) == k && k >= 1) {
    767                if (k > max)
    768                    max = k;
    769                items++;
    770                lua_pop(l, 1);
    771                continue;
    772            }
    773        }
    774 
    775        /* Must not be an array (non integer key) */
    776        lua_pop(l, 2);
    777        return -1;
    778    }
    779 
    780    /* Encode excessively sparse arrays as objects (if enabled) */
    781    if (cfg->encode_sparse_ratio > 0 &&
    782        max > items * cfg->encode_sparse_ratio &&
    783        max > cfg->encode_sparse_safe) {
    784        if (!cfg->encode_sparse_convert)
    785            json_encode_exception(l, ctx, -1, "excessively sparse array");
    786 
    787        return -1;
    788    }
    789 
    790    return max;
    791 }
    792 
    793 static void json_check_encode_depth(lua_State *l, json_config_t *cfg,
    794                                    int current_depth, strbuf_t *json)
    795 {
    796    /* Ensure there are enough slots free to traverse a table (key,
    797     * value) and push a string for a potential error message.
    798     *
    799     * Unlike "decode", the key and value are still on the stack when
    800     * lua_checkstack() is called.  Hence an extra slot for luaL_error()
    801     * below is required just in case the next check to lua_checkstack()
    802     * fails.
    803     *
    804     * While this won't cause a crash due to the EXTRA_STACK reserve
    805     * slots, it would still be an improper use of the API. */
    806    if (current_depth <= cfg->encode_max_depth && lua_checkstack(l, 3))
    807        return;
    808 
    809    if (!cfg->encode_keep_buffer)
    810        strbuf_free(json);
    811 
    812    luaL_error(l, "Cannot serialise, excessive nesting (%d)",
    813               current_depth);
    814 }
    815 
    816 static int json_append_data(lua_State *l, json_encode_t *cfg,
    817                             int current_depth);
    818 
    819 static void json_append_newline_and_indent(strbuf_t *json, json_encode_t *ctx, int depth)
    820 {
    821    strbuf_append_char(json, '\n');
    822    for (int i = 0; i < depth; i++)
    823        strbuf_append_string(json, ctx->options->indent);
    824 }
    825 
    826 /* json_append_array args:
    827 * - lua_State
    828 * - JSON strbuf
    829 * - Size of passed Lua array (top of stack) */
    830 static void json_append_array(lua_State *l, json_encode_t *ctx, int current_depth,
    831                              int array_length, int raw)
    832 {
    833    int comma, i, json_pos, err;
    834    int has_items = 0;
    835    strbuf_t *json = ctx->json;
    836 
    837    strbuf_append_char(json, '[');
    838 
    839    comma = 0;
    840    for (i = 1; i <= array_length; i++) {
    841        has_items = 1;
    842 
    843        json_pos = strbuf_length(json);
    844        if (comma++ > 0)
    845            strbuf_append_char(json, ',');
    846 
    847        if (ctx->options->indent)
    848            json_append_newline_and_indent(json, ctx, current_depth);
    849 
    850        if (raw) {
    851            lua_rawgeti(l, -1, i);
    852        } else {
    853            #if LUA_VERSION_NUM >= 503
    854             lua_geti(l, -1, i);
    855            #else
    856             lua_pushinteger(l, i);
    857             lua_gettable(l, -2);
    858            #endif
    859        }
    860 
    861        err = json_append_data(l, ctx, current_depth);
    862        if (err) {
    863            strbuf_set_length(json, json_pos);
    864            if (comma == 1) {
    865                comma = 0;
    866            }
    867        }
    868        lua_pop(l, 1);
    869    }
    870 
    871    if (has_items && ctx->options->indent)
    872        json_append_newline_and_indent(json, ctx, current_depth-1);
    873 
    874    strbuf_append_char(json, ']');
    875 }
    876 
    877 static void json_append_number(lua_State *l, json_encode_t *ctx,
    878                               int lindex, int use_keybuf)
    879 {
    880    int len;
    881    #if LUA_VERSION_NUM >= 503
    882     if (lua_isinteger(l, lindex)) {
    883         lua_Integer num = lua_tointeger(l, lindex);
    884         strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE); /* max length of int64 is 19 */
    885         len = sprintf(strbuf_empty_ptr(json), LUA_INTEGER_FMT, num);
    886         strbuf_extend_length(json, len);
    887         return;
    888     }
    889    #endif
    890    double num = lua_tonumber(l, lindex);
    891    json_config_t *cfg = ctx->cfg;
    892    strbuf_t *json = ctx->json;
    893    if (use_keybuf) {
    894        json = &ctx->options->keybuf.buf;
    895    }
    896 
    897    if (cfg->encode_invalid_numbers == 0) {
    898        /* Prevent encoding invalid numbers */
    899        if (isinf(num) || isnan(num))
    900            json_encode_exception(l, ctx, lindex,
    901                                  "must not be NaN or Infinity");
    902    } else if (cfg->encode_invalid_numbers == 1) {
    903        /* Encode NaN/Infinity separately to ensure Javascript compatible
    904         * values are used. */
    905        if (isnan(num)) {
    906            strbuf_append_mem(json, "NaN", 3);
    907            return;
    908        }
    909        if (isinf(num)) {
    910            if (num < 0)
    911                strbuf_append_mem(json, "-Infinity", 9);
    912            else
    913                strbuf_append_mem(json, "Infinity", 8);
    914            return;
    915        }
    916    } else {
    917        /* Encode invalid numbers as "null" */
    918        if (isinf(num) || isnan(num)) {
    919            strbuf_append_mem(json, "null", 4);
    920            return;
    921        }
    922    }
    923 
    924    strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE);
    925    len = fpconv_g_fmt(strbuf_empty_ptr(json), num, cfg->encode_number_precision);
    926    strbuf_extend_length(json, len);
    927 }
    928 
    929 /* Compare key_entry_t for qsort. */
    930 static int cmp_key_entries(const void *a, const void *b) {
    931    const key_entry_t *ka = a;
    932    const key_entry_t *kb = b;
    933    int res = memcmp(ka->buf->buf + ka->offset,
    934                     kb->buf->buf + kb->offset,
    935                     ka->length < kb->length ? ka->length : kb->length);
    936    if (res == 0)
    937        return (ka->length - kb->length);
    938    return res;
    939 }
    940 
    941 static void json_append_object(lua_State *l, json_encode_t *ctx,
    942                               int current_depth)
    943 {
    944    int comma, keytype, json_pos, err;
    945    int has_items = 0;
    946    strbuf_t *json = ctx->json;
    947 
    948    /* Object */
    949    strbuf_append_char(json, '{');
    950 
    951    comma = 0;
    952    lua_pushnil(l);
    953    if (ctx->options->sort_keys) {
    954        keybuf_t *keybuf = &ctx->options->keybuf;
    955        size_t init_keybuf_size = keybuf->size;
    956        size_t init_keybuf_length = strbuf_length(&keybuf->buf);
    957 
    958        while (lua_next(l, -2) != 0) {
    959            has_items = 1;
    960            if (keybuf->size == keybuf->capacity) {
    961                keybuf->capacity *= 2;
    962                key_entry_t *tmp = realloc(keybuf->keys,
    963                                           keybuf->capacity * sizeof(key_entry_t));
    964                if (!tmp)
    965                    json_encode_exception(l, ctx, -1, "out of memory");
    966                keybuf->keys = tmp;
    967            }
    968 
    969            keytype = lua_type(l, -2);
    970            key_entry_t key_entry = {
    971                .buf = &keybuf->buf,
    972                .offset = strbuf_length(&keybuf->buf),
    973                .raw_typ = keytype,
    974            };
    975            if (keytype == LUA_TSTRING) {
    976                json_append_string_contents(l, ctx, -2, true);
    977                key_entry.raw.string = lua_tostring(l, -2);
    978            } else if (keytype == LUA_TNUMBER) {
    979                json_append_number(l, ctx, -2, true);
    980                key_entry.raw.number = lua_tointeger(l, -2);
    981            } else {
    982                json_encode_exception(l, ctx, -2,
    983                                      "table key must be number or string");
    984            }
    985            key_entry.length = strbuf_length(&keybuf->buf) - key_entry.offset;
    986            keybuf->keys[keybuf->size++] = key_entry;
    987            lua_pop(l, 1);
    988        }
    989 
    990        size_t keys_count = keybuf->size - init_keybuf_size;
    991        qsort(keybuf->keys + init_keybuf_size, keys_count,
    992              sizeof (key_entry_t), cmp_key_entries);
    993 
    994        for (size_t i = init_keybuf_size; i < init_keybuf_size + keys_count; i++) {
    995            key_entry_t *current_key = &keybuf->keys[i];
    996            json_pos = strbuf_length(json);
    997            if (comma++ > 0)
    998                strbuf_append_char(json, ',');
    999 
   1000            if (ctx->options->indent)
   1001                json_append_newline_and_indent(json, ctx, current_depth);
   1002 
   1003            strbuf_ensure_empty_length(json, current_key->length + 3);
   1004            strbuf_append_char_unsafe(json, '"');
   1005            strbuf_append_mem_unsafe(json, keybuf->buf.buf + current_key->offset,
   1006                                     current_key->length);
   1007            strbuf_append_mem_unsafe(json, "\":", 2);
   1008 
   1009            if (ctx->options->indent)
   1010                strbuf_append_char(json, ' ');
   1011 
   1012            if (current_key->raw_typ == LUA_TSTRING)
   1013                lua_pushstring(l, current_key->raw.string);
   1014            else
   1015                lua_pushnumber(l, current_key->raw.number);
   1016 
   1017            lua_gettable(l, -2);
   1018            err = json_append_data(l, ctx, current_depth);
   1019            if (err) {
   1020                strbuf_set_length(json, json_pos);
   1021                if (comma == 1)
   1022                    comma = 0;
   1023            }
   1024            lua_pop(l, 1);
   1025        }
   1026        /* resize encode_keybuf to reuse allocated memory for forward keys */
   1027        strbuf_set_length(&keybuf->buf, init_keybuf_length);
   1028        keybuf->size = init_keybuf_size;
   1029    } else {
   1030        while (lua_next(l, -2) != 0) {
   1031            has_items = 1;
   1032 
   1033            json_pos = strbuf_length(json);
   1034            if (comma++ > 0)
   1035                strbuf_append_char(json, ',');
   1036 
   1037            if (ctx->options->indent)
   1038                json_append_newline_and_indent(json, ctx, current_depth);
   1039 
   1040            /* table, key, value */
   1041            keytype = lua_type(l, -2);
   1042            if (keytype == LUA_TNUMBER) {
   1043                strbuf_append_char(json, '"');
   1044                json_append_number(l, ctx, -2, false);
   1045                strbuf_append_mem(json, "\":", 2);
   1046            } else if (keytype == LUA_TSTRING) {
   1047                json_append_string(l, ctx, -2);
   1048                strbuf_append_char(json, ':');
   1049            } else {
   1050                json_encode_exception(l, ctx, -2,
   1051                                      "table key must be a number or string");
   1052                /* never returns */
   1053            }
   1054            if (ctx->options->indent)
   1055                strbuf_append_char(json, ' ');
   1056 
   1057            /* table, key, value */
   1058            err = json_append_data(l, ctx, current_depth);
   1059            if (err) {
   1060                strbuf_set_length(json, json_pos);
   1061                if (comma == 1)
   1062                    comma = 0;
   1063            }
   1064 
   1065            lua_pop(l, 1);
   1066            /* table, key */
   1067        }
   1068    }
   1069 
   1070    if (has_items && ctx->options->indent)
   1071        json_append_newline_and_indent(json, ctx, current_depth-1);
   1072 
   1073    strbuf_append_char(json, '}');
   1074 }
   1075 
   1076 /* Serialise Lua data into JSON string. Return 1 if an error happened, else 0. */
   1077 static int json_append_data(lua_State *l, json_encode_t *ctx,
   1078                             int current_depth)
   1079 {
   1080    int len;
   1081    int as_array = 0;
   1082    int as_empty_dict = 0;
   1083    int has_metatable;
   1084    int raw = 1;
   1085    json_config_t *cfg = ctx->cfg;
   1086    strbuf_t *json = ctx->json;
   1087 
   1088    switch (lua_type(l, -1)) {
   1089    case LUA_TSTRING:
   1090        json_append_string(l, ctx, -1);
   1091        break;
   1092    case LUA_TNUMBER:
   1093        json_append_number(l, ctx, -1, false);
   1094        break;
   1095    case LUA_TBOOLEAN:
   1096        if (lua_toboolean(l, -1))
   1097            strbuf_append_mem(json, "true", 4);
   1098        else
   1099            strbuf_append_mem(json, "false", 5);
   1100        break;
   1101    case LUA_TTABLE:
   1102        current_depth++;
   1103        json_check_encode_depth(l, cfg, current_depth, json);
   1104 
   1105        has_metatable = lua_getmetatable(l, -1);
   1106 
   1107        if (has_metatable) {
   1108 
   1109          nlua_pushref(l, nlua_get_empty_dict_ref(l));
   1110          if (lua_rawequal(l, -2, -1)) {
   1111            as_empty_dict = true;
   1112          } else {
   1113            lua_pop(l, 1);
   1114            lua_pushlightuserdata(l, json_lightudata_mask(&json_array));
   1115            lua_rawget(l, LUA_REGISTRYINDEX);
   1116            as_array = lua_rawequal(l, -1, -2);
   1117          }
   1118            if (as_array) {
   1119                raw = 1;
   1120                lua_pop(l, 2);
   1121                len = lua_objlen(l, -1);
   1122            } else {
   1123                raw = 0;
   1124                lua_pop(l, 2);
   1125                if (luaL_getmetafield(l, -1, "__len")) {
   1126                    lua_pushvalue(l, -2);
   1127                    lua_call(l, 1, 1);
   1128                    len = lua_tonumber(l, -1);
   1129                    lua_pop(l, 1);
   1130                    as_array = 1;
   1131                }
   1132            }
   1133        }
   1134 
   1135        if (as_array) {
   1136            len = lua_objlen(l, -1);
   1137            json_append_array(l, ctx, current_depth, len, raw);
   1138        } else {
   1139            len = lua_array_length(l, ctx);
   1140 
   1141            if (len > 0 || (len == 0 && !cfg->encode_empty_table_as_object && !as_empty_dict)) {
   1142                json_append_array(l, ctx, current_depth, len, raw);
   1143            } else {
   1144                if (has_metatable) {
   1145                    lua_getmetatable(l, -1);
   1146                    lua_pushlightuserdata(l, json_lightudata_mask(
   1147                                          &json_empty_array));
   1148                    lua_rawget(l, LUA_REGISTRYINDEX);
   1149                    as_array = lua_rawequal(l, -1, -2);
   1150                    lua_pop(l, 2); /* pop pointer + metatable */
   1151                    if (as_array) {
   1152                        len = lua_objlen(l, -1);
   1153 
   1154                        raw = 1;
   1155                        json_append_array(l, ctx, current_depth, len, raw);
   1156                        break;
   1157                    }
   1158                }
   1159                json_append_object(l, ctx, current_depth);
   1160            }
   1161        }
   1162        break;
   1163    case LUA_TNIL:
   1164        strbuf_append_mem(json, "null", 4);
   1165        break;
   1166    case LUA_TLIGHTUSERDATA:
   1167        if (lua_touserdata(l, -1) == &json_array) {
   1168            json_append_array(l, ctx, current_depth, 0, 1);
   1169        }
   1170        break;
   1171    case LUA_TUSERDATA:
   1172        nlua_pushref(l, nlua_get_nil_ref(l));
   1173        bool is_nil = lua_rawequal(l, -2, -1);
   1174        lua_pop(l, 1);
   1175        if (is_nil) {
   1176            strbuf_append_mem(json, "null", 4);
   1177            break;
   1178        } else {
   1179          FALLTHROUGH;
   1180        }
   1181    default:
   1182        /* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD,
   1183         * and LUA_TLIGHTUSERDATA) cannot be serialised */
   1184        if (cfg->encode_skip_unsupported_value_types) {
   1185                return 1;
   1186            } else {
   1187        json_encode_exception(l, ctx, -1, "type not supported");
   1188            }
   1189 
   1190        /* never returns */
   1191    }
   1192    return 0;
   1193 }
   1194 
   1195 static int json_encode(lua_State *l)
   1196 {
   1197    json_config_t *cfg = json_fetch_config(l);
   1198    json_encode_options_t options = {
   1199        .char2escape = { char2escape },
   1200        .indent = DEFAULT_ENCODE_INDENT,
   1201        .sort_keys = DEFAULT_ENCODE_SORT_KEYS,
   1202    };
   1203    json_encode_t ctx = { .options = &options, .cfg = cfg };
   1204    strbuf_t local_encode_buf;
   1205    strbuf_t *encode_buf;
   1206    char *json;
   1207    size_t len;
   1208    const char *customChar2escape[256];
   1209 
   1210    switch (lua_gettop(l)) {
   1211    case 1:
   1212        break;
   1213    case 2:
   1214        luaL_checktype(l, 2, LUA_TTABLE);
   1215 
   1216        lua_getfield(l, 2, "escape_slash");
   1217        if (!lua_isnil(l, -1)) {
   1218            luaL_checktype(l, -1, LUA_TBOOLEAN);
   1219 
   1220            int escape_slash = lua_toboolean(l, -1);
   1221            if (escape_slash) {
   1222                /* This can be optimised by adding a new hard-coded escape table for this case,
   1223                 * but this path will rarely if ever be used, so let's just memcpy. */
   1224                memcpy(customChar2escape, char2escape, sizeof(char2escape));
   1225                customChar2escape['/'] = "\\/";
   1226                *ctx.options->char2escape = customChar2escape;
   1227            }
   1228        }
   1229        lua_pop(l, 1);
   1230 
   1231        lua_getfield(l, 2, "indent");
   1232        if (!lua_isnil(l, -1)) {
   1233            options.indent = luaL_checkstring(l, -1);
   1234            if (options.indent[0] == '\0') options.indent = NULL;
   1235        }
   1236        lua_pop(l, 1);
   1237 
   1238        lua_getfield(l, 2, "sort_keys");
   1239        if (!lua_isnil(l, -1)) {
   1240            luaL_checktype(l, -1, LUA_TBOOLEAN);
   1241 
   1242            int sort_keys = lua_toboolean(l, -1);
   1243            if (sort_keys) {
   1244                options.sort_keys = sort_keys;
   1245                strbuf_init(&options.keybuf.buf, 0);
   1246                options.keybuf.size = 0;
   1247                options.keybuf.capacity = KEYBUF_DEFAULT_CAPACITY;
   1248                options.keybuf.keys = malloc(options.keybuf.capacity * sizeof(key_entry_t));
   1249                if (!options.keybuf.keys)
   1250                    return luaL_error (l, "out of memory");
   1251            }
   1252        }
   1253 
   1254        /* Also pop the opts table */
   1255        lua_pop(l, 2);
   1256        break;
   1257    default:
   1258        return luaL_error (l, "expected 1 or 2 arguments");
   1259    }
   1260 
   1261    if (!cfg->encode_keep_buffer) {
   1262        /* Use private buffer */
   1263        encode_buf = &local_encode_buf;
   1264        strbuf_init(encode_buf, 0);
   1265    } else {
   1266        /* Reuse existing buffer */
   1267        encode_buf = &cfg->encode_buf;
   1268        strbuf_reset(encode_buf);
   1269    }
   1270 
   1271    ctx.json = encode_buf;
   1272    json_append_data(l, &ctx, 0);
   1273    json = strbuf_string(encode_buf, &len);
   1274 
   1275    lua_pushlstring(l, json, len);
   1276 
   1277    if (!cfg->encode_keep_buffer)
   1278        strbuf_free(encode_buf);
   1279 
   1280    if (options.sort_keys) {
   1281        strbuf_free(&options.keybuf.buf);
   1282        free(options.keybuf.keys);
   1283    }
   1284 
   1285    return 1;
   1286 }
   1287 
   1288 /* ===== DECODING ===== */
   1289 
   1290 static void json_process_value(lua_State *l, json_parse_t *json,
   1291                               json_token_t *token, bool use_luanil);
   1292 
   1293 static int hexdigit2int(char hex)
   1294 {
   1295    if ('0' <= hex  && hex <= '9')
   1296        return hex - '0';
   1297 
   1298    /* Force lowercase */
   1299    hex |= 0x20;
   1300    if ('a' <= hex && hex <= 'f')
   1301        return 10 + hex - 'a';
   1302 
   1303    return -1;
   1304 }
   1305 
   1306 static int decode_hex4(const char *hex)
   1307 {
   1308    int digit[4];
   1309    int i;
   1310 
   1311    /* Convert ASCII hex digit to numeric digit
   1312     * Note: this returns an error for invalid hex digits, including
   1313     *       NULL */
   1314    for (i = 0; i < 4; i++) {
   1315        digit[i] = hexdigit2int(hex[i]);
   1316        if (digit[i] < 0) {
   1317            return -1;
   1318        }
   1319    }
   1320 
   1321    return (digit[0] << 12) +
   1322           (digit[1] << 8) +
   1323           (digit[2] << 4) +
   1324            digit[3];
   1325 }
   1326 
   1327 /* Converts a Unicode codepoint to UTF-8.
   1328 * Returns UTF-8 string length, and up to 4 bytes in *utf8 */
   1329 static int codepoint_to_utf8(char *utf8, int codepoint)
   1330 {
   1331    /* 0xxxxxxx */
   1332    if (codepoint <= 0x7F) {
   1333        utf8[0] = codepoint;
   1334        return 1;
   1335    }
   1336 
   1337    /* 110xxxxx 10xxxxxx */
   1338    if (codepoint <= 0x7FF) {
   1339        utf8[0] = (codepoint >> 6) | 0xC0;
   1340        utf8[1] = (codepoint & 0x3F) | 0x80;
   1341        return 2;
   1342    }
   1343 
   1344    /* 1110xxxx 10xxxxxx 10xxxxxx */
   1345    if (codepoint <= 0xFFFF) {
   1346        utf8[0] = (codepoint >> 12) | 0xE0;
   1347        utf8[1] = ((codepoint >> 6) & 0x3F) | 0x80;
   1348        utf8[2] = (codepoint & 0x3F) | 0x80;
   1349        return 3;
   1350    }
   1351 
   1352    /* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */
   1353    if (codepoint <= 0x1FFFFF) {
   1354        utf8[0] = (codepoint >> 18) | 0xF0;
   1355        utf8[1] = ((codepoint >> 12) & 0x3F) | 0x80;
   1356        utf8[2] = ((codepoint >> 6) & 0x3F) | 0x80;
   1357        utf8[3] = (codepoint & 0x3F) | 0x80;
   1358        return 4;
   1359    }
   1360 
   1361    return 0;
   1362 }
   1363 
   1364 
   1365 /* Called when index pointing to beginning of UTF-16 code escape: \uXXXX
   1366 * \u is guaranteed to exist, but the remaining hex characters may be
   1367 * missing.
   1368 * Translate to UTF-8 and append to temporary token string.
   1369 * Must advance index to the next character to be processed.
   1370 * Returns: 0   success
   1371 *          -1  error
   1372 */
   1373 static int json_append_unicode_escape(json_parse_t *json)
   1374 {
   1375    char utf8[4];       /* Surrogate pairs require 4 UTF-8 bytes */
   1376    int codepoint;
   1377    int surrogate_low;
   1378    int len;
   1379    int escape_len = 6;
   1380 
   1381    /* Fetch UTF-16 code unit */
   1382    codepoint = decode_hex4(json->ptr + 2);
   1383    if (codepoint < 0)
   1384        return -1;
   1385 
   1386    /* UTF-16 surrogate pairs take the following 2 byte form:
   1387     *      11011 x yyyyyyyyyy
   1388     * When x = 0: y is the high 10 bits of the codepoint
   1389     *      x = 1: y is the low 10 bits of the codepoint
   1390     *
   1391     * Check for a surrogate pair (high or low) */
   1392    if ((codepoint & 0xF800) == 0xD800) {
   1393        /* Error if the 1st surrogate is not high */
   1394        if (codepoint & 0x400)
   1395            return -1;
   1396 
   1397        /* Ensure the next code is a unicode escape */
   1398        if (*(json->ptr + escape_len) != '\\' ||
   1399            *(json->ptr + escape_len + 1) != 'u') {
   1400            return -1;
   1401        }
   1402 
   1403        /* Fetch the next codepoint */
   1404        surrogate_low = decode_hex4(json->ptr + 2 + escape_len);
   1405        if (surrogate_low < 0)
   1406            return -1;
   1407 
   1408        /* Error if the 2nd code is not a low surrogate */
   1409        if ((surrogate_low & 0xFC00) != 0xDC00)
   1410            return -1;
   1411 
   1412        /* Calculate Unicode codepoint */
   1413        codepoint = (codepoint & 0x3FF) << 10;
   1414        surrogate_low &= 0x3FF;
   1415        codepoint = (codepoint | surrogate_low) + 0x10000;
   1416        escape_len = 12;
   1417    }
   1418 
   1419    /* Convert codepoint to UTF-8 */
   1420    len = codepoint_to_utf8(utf8, codepoint);
   1421    if (!len)
   1422        return -1;
   1423 
   1424    /* Append bytes and advance parse index */
   1425    strbuf_append_mem_unsafe(json->tmp, utf8, len);
   1426    json->ptr += escape_len;
   1427 
   1428    return 0;
   1429 }
   1430 
   1431 static void json_set_token_error(json_token_t *token, json_parse_t *json,
   1432                                 const char *errtype)
   1433 {
   1434    token->type = T_ERROR;
   1435    token->index = json->ptr - json->data;
   1436    token->value.string = errtype;
   1437 }
   1438 
   1439 static void json_next_string_token(json_parse_t *json, json_token_t *token)
   1440 {
   1441    char *escape2char = json->cfg->escape2char;
   1442    char ch;
   1443 
   1444    /* Caller must ensure a string is next */
   1445    assert(*json->ptr == '"');
   1446 
   1447    /* Skip " */
   1448    json->ptr++;
   1449 
   1450    /* json->tmp is the temporary strbuf used to accumulate the
   1451     * decoded string value.
   1452     * json->tmp is sized to handle JSON containing only a string value.
   1453     */
   1454    strbuf_reset(json->tmp);
   1455 
   1456    while ((ch = *json->ptr) != '"') {
   1457        if (!ch) {
   1458            /* Premature end of the string */
   1459            json_set_token_error(token, json, "unexpected end of string");
   1460            return;
   1461        }
   1462 
   1463        /* Handle escapes */
   1464        if (ch == '\\') {
   1465            /* Fetch escape character */
   1466            ch = *(json->ptr + 1);
   1467 
   1468            /* Translate escape code and append to tmp string */
   1469            ch = escape2char[(unsigned char)ch];
   1470            if (ch == 'u') {
   1471                if (json_append_unicode_escape(json) == 0)
   1472                    continue;
   1473 
   1474                json_set_token_error(token, json,
   1475                                     "invalid unicode escape code");
   1476                return;
   1477            }
   1478            if (!ch) {
   1479                json_set_token_error(token, json, "invalid escape code");
   1480                return;
   1481            }
   1482 
   1483            /* Skip '\' */
   1484            json->ptr++;
   1485        }
   1486        /* Append normal character or translated single character
   1487         * Unicode escapes are handled above */
   1488        strbuf_append_char_unsafe(json->tmp, ch);
   1489        json->ptr++;
   1490    }
   1491    json->ptr++;    /* Eat final quote (") */
   1492 
   1493    strbuf_ensure_null(json->tmp);
   1494 
   1495    token->type = T_STRING;
   1496    token->value.string = strbuf_string(json->tmp, &token->string_len);
   1497 }
   1498 
   1499 /* JSON numbers should take the following form:
   1500 *      -?(0|[1-9]|[1-9][0-9]+)(.[0-9]+)?([eE][-+]?[0-9]+)?
   1501 *
   1502 * json_next_number_token() uses strtod() which allows other forms:
   1503 * - numbers starting with '+'
   1504 * - NaN, -NaN, infinity, -infinity
   1505 * - hexadecimal numbers
   1506 * - numbers with leading zeros
   1507 *
   1508 * json_is_invalid_number() detects "numbers" which may pass strtod()'s
   1509 * error checking, but should not be allowed with strict JSON.
   1510 *
   1511 * json_is_invalid_number() may pass numbers which cause strtod()
   1512 * to generate an error.
   1513 */
   1514 static int json_is_invalid_number(json_parse_t *json)
   1515 {
   1516    const char *p = json->ptr;
   1517 
   1518    /* Reject numbers starting with + */
   1519    if (*p == '+')
   1520        return 1;
   1521 
   1522    /* Skip minus sign if it exists */
   1523    if (*p == '-')
   1524        p++;
   1525 
   1526    /* Reject numbers starting with 0x, or leading zeros */
   1527    if (*p == '0') {
   1528        char ch2 = *(p + 1);
   1529 
   1530        if ((ch2 | 0x20) == 'x' ||          /* Hex */
   1531            ('0' <= ch2 && ch2 <= '9'))     /* Leading zero */
   1532            return 1;
   1533 
   1534        return 0;
   1535    } else if (*p <= '9') {
   1536        return 0;                           /* Ordinary number */
   1537    }
   1538 
   1539    /* Reject inf/nan */
   1540    if (!strncasecmp(p, "inf", 3))
   1541        return 1;
   1542    if (!strncasecmp(p, "nan", 3))
   1543        return 1;
   1544 
   1545    /* Pass all other numbers which may still be invalid, but
   1546     * strtod() will catch them. */
   1547    return 0;
   1548 }
   1549 
   1550 static void json_next_number_token(json_parse_t *json, json_token_t *token)
   1551 {
   1552    char *endptr;
   1553 
   1554    long long tmpval = strtoll(json->ptr, &endptr, 10);
   1555    if (json->ptr == endptr || *endptr == '.' || *endptr == 'e' ||
   1556        *endptr == 'E' || *endptr == 'x') {
   1557        token->type = T_NUMBER;
   1558        token->value.number = fpconv_strtod(json->ptr, &endptr);
   1559        if (json->ptr == endptr) {
   1560            json_set_token_error(token, json, "invalid number");
   1561            return;
   1562        }
   1563    } else if (tmpval > PTRDIFF_MAX || tmpval < PTRDIFF_MIN) {
   1564        /* Typical Lua builds typedef ptrdiff_t to lua_Integer. If tmpval is
   1565         * outside the range of that type, we need to use T_NUMBER to avoid
   1566         * truncation.
   1567         */
   1568        token->type = T_NUMBER;
   1569        token->value.number = tmpval;
   1570    } else {
   1571        token->type = T_INTEGER;
   1572        token->value.integer = tmpval;
   1573    }
   1574    json->ptr = endptr;     /* Skip the processed number */
   1575 
   1576    return;
   1577 }
   1578 
   1579 /* Fills in the token struct.
   1580 * T_STRING will return a pointer to the json_parse_t temporary string
   1581 * T_ERROR will leave the json->ptr pointer at the error.
   1582 */
   1583 static void json_next_token(json_parse_t *json, json_token_t *token)
   1584 {
   1585    const json_token_type_t *ch2token = json->cfg->ch2token;
   1586    int ch;
   1587 
   1588    while (1) {
   1589        /* Eat whitespace. */
   1590        while (1) {
   1591            ch = (unsigned char)*(json->ptr);
   1592            token->type = ch2token[ch];
   1593            if (token->type != T_WHITESPACE)
   1594                break;
   1595            json->ptr++;
   1596        }
   1597 
   1598        if (!json->options->skip_comments)
   1599            break;
   1600 
   1601        /* Eat comments. */
   1602        if ((unsigned char)json->ptr[0] != '/' ||
   1603            ((unsigned char)json->ptr[1] != '/' &&
   1604            (unsigned char)json->ptr[1] != '*')) {
   1605            break;
   1606        }
   1607 
   1608        if (json->ptr[1] == '/') {
   1609            /* Handle single-line comment */
   1610            json->ptr += 2;
   1611            while (*json->ptr != '\0' && *json->ptr != '\n')
   1612                json->ptr++;
   1613        } else {
   1614            /* Handle multi-line comment */
   1615            json->ptr += 2;
   1616            while (1) {
   1617                if (*json->ptr == '\0') {
   1618                    json_set_token_error(token, json, "unclosed multi-line comment");
   1619                    return;
   1620                }
   1621                if (json->ptr[0] == '*' && json->ptr[1] == '/') {
   1622                    json->ptr += 2;
   1623                    break;
   1624                }
   1625                json->ptr++;
   1626            }
   1627        }
   1628    }
   1629 
   1630    /* Store location of new token. Required when throwing errors
   1631     * for unexpected tokens (syntax errors). */
   1632    token->index = json->ptr - json->data;
   1633 
   1634    /* Don't advance the pointer for an error or the end */
   1635    if (token->type == T_ERROR) {
   1636        json_set_token_error(token, json, "invalid token");
   1637        return;
   1638    }
   1639 
   1640    if (token->type == T_END) {
   1641        return;
   1642    }
   1643 
   1644    /* Found a known single character token, advance index and return */
   1645    if (token->type != T_UNKNOWN) {
   1646        json->ptr++;
   1647        return;
   1648    }
   1649 
   1650    /* Process characters which triggered T_UNKNOWN
   1651     *
   1652     * Must use strncmp() to match the front of the JSON string.
   1653     * JSON identifier must be lowercase.
   1654     * When strict_numbers if disabled, either case is allowed for
   1655     * Infinity/NaN (since we are no longer following the spec..) */
   1656    if (ch == '"') {
   1657        json_next_string_token(json, token);
   1658        return;
   1659    } else if (ch == '-' || ('0' <= ch && ch <= '9')) {
   1660        if (!json->cfg->decode_invalid_numbers && json_is_invalid_number(json)) {
   1661            json_set_token_error(token, json, "invalid number");
   1662            return;
   1663        }
   1664        json_next_number_token(json, token);
   1665        return;
   1666    } else if (!strncmp(json->ptr, "true", 4)) {
   1667        token->type = T_BOOLEAN;
   1668        token->value.boolean = 1;
   1669        json->ptr += 4;
   1670        return;
   1671    } else if (!strncmp(json->ptr, "false", 5)) {
   1672        token->type = T_BOOLEAN;
   1673        token->value.boolean = 0;
   1674        json->ptr += 5;
   1675        return;
   1676    } else if (!strncmp(json->ptr, "null", 4)) {
   1677        token->type = T_NULL;
   1678        json->ptr += 4;
   1679        return;
   1680    } else if (json->cfg->decode_invalid_numbers &&
   1681               json_is_invalid_number(json)) {
   1682        /* When decode_invalid_numbers is enabled, only attempt to process
   1683         * numbers we know are invalid JSON (Inf, NaN, hex)
   1684         * This is required to generate an appropriate token error,
   1685         * otherwise all bad tokens will register as "invalid number"
   1686         */
   1687        json_next_number_token(json, token);
   1688        return;
   1689    }
   1690 
   1691    /* Token starts with t/f/n but isn't recognised above. */
   1692    json_set_token_error(token, json, "invalid token");
   1693 }
   1694 
   1695 /* This function does not return.
   1696 * DO NOT CALL WITH DYNAMIC MEMORY ALLOCATED.
   1697 * The only supported exception is the temporary parser string
   1698 * json->tmp struct.
   1699 * json and token should exist on the stack somewhere.
   1700 * luaL_error() will long_jmp and release the stack */
   1701 static void json_throw_parse_error(lua_State *l, json_parse_t *json,
   1702                                   const char *exp, json_token_t *token)
   1703 {
   1704    const char *found;
   1705 
   1706    strbuf_free(json->tmp);
   1707 
   1708    if (token->type == T_ERROR)
   1709        found = token->value.string;
   1710    else
   1711        found = json_token_type_name[token->type];
   1712 
   1713    /* Note: token->index is 0 based, display starting from 1 */
   1714    luaL_error(l, "Expected %s but found %s at character %d",
   1715               exp, found, token->index + 1);
   1716 }
   1717 
   1718 static inline void json_decode_ascend(json_parse_t *json)
   1719 {
   1720    json->current_depth--;
   1721 }
   1722 
   1723 static void json_decode_descend(lua_State *l, json_parse_t *json, int slots)
   1724 {
   1725    json->current_depth++;
   1726 
   1727    if (json->current_depth <= json->cfg->decode_max_depth &&
   1728        lua_checkstack(l, slots)) {
   1729        return;
   1730    }
   1731 
   1732    strbuf_free(json->tmp);
   1733    luaL_error(l, "Found too many nested data structures (%d) at character %d",
   1734        json->current_depth, json->ptr - json->data);
   1735 }
   1736 
   1737 static void json_parse_object_context(lua_State *l, json_parse_t *json)
   1738 {
   1739    json_token_t token;
   1740 
   1741    /* 3 slots required:
   1742     * .., table, key, value */
   1743    json_decode_descend(l, json, 3);
   1744 
   1745    lua_newtable(l);
   1746 
   1747    json_next_token(json, &token);
   1748 
   1749    /* Handle empty objects */
   1750    if (token.type == T_OBJ_END) {
   1751        nlua_pushref(l, nlua_get_empty_dict_ref(l)); \
   1752        lua_setmetatable(l, -2); \
   1753        json_decode_ascend(json);
   1754        return;
   1755    }
   1756 
   1757    while (1) {
   1758        if (token.type != T_STRING)
   1759            json_throw_parse_error(l, json, "object key string", &token);
   1760 
   1761        /* Push key */
   1762        lua_pushlstring(l, token.value.string, token.string_len);
   1763 
   1764        json_next_token(json, &token);
   1765        if (token.type != T_COLON)
   1766            json_throw_parse_error(l, json, "colon", &token);
   1767 
   1768        /* Fetch value */
   1769        json_next_token(json, &token);
   1770        json_process_value(l, json, &token, json->options->luanil_object);
   1771 
   1772        /* Set key = value */
   1773        lua_rawset(l, -3);
   1774 
   1775        json_next_token(json, &token);
   1776 
   1777        if (token.type == T_OBJ_END) {
   1778            json_decode_ascend(json);
   1779            return;
   1780        }
   1781 
   1782        if (token.type != T_COMMA)
   1783            json_throw_parse_error(l, json, "comma or object end", &token);
   1784 
   1785        json_next_token(json, &token);
   1786    }
   1787 }
   1788 
   1789 /* Handle the array context */
   1790 static void json_parse_array_context(lua_State *l, json_parse_t *json)
   1791 {
   1792    json_token_t token;
   1793    int i;
   1794 
   1795    /* 2 slots required:
   1796     * .., table, value */
   1797    json_decode_descend(l, json, 2);
   1798 
   1799    lua_newtable(l);
   1800 
   1801    /* set array_mt on the table at the top of the stack */
   1802    if (json->cfg->decode_array_with_array_mt) {
   1803        lua_pushlightuserdata(l, json_lightudata_mask(&json_array));
   1804        lua_rawget(l, LUA_REGISTRYINDEX);
   1805        lua_setmetatable(l, -2);
   1806    }
   1807 
   1808    json_next_token(json, &token);
   1809 
   1810    /* Handle empty arrays */
   1811    if (token.type == T_ARR_END) {
   1812        json_decode_ascend(json);
   1813        return;
   1814    }
   1815 
   1816    for (i = 1; ; i++) {
   1817        json_process_value(l, json, &token, json->options->luanil_array);
   1818        lua_rawseti(l, -2, i);            /* arr[i] = value */
   1819 
   1820        json_next_token(json, &token);
   1821 
   1822        if (token.type == T_ARR_END) {
   1823            json_decode_ascend(json);
   1824            return;
   1825        }
   1826 
   1827        if (token.type != T_COMMA)
   1828            json_throw_parse_error(l, json, "comma or array end", &token);
   1829 
   1830        json_next_token(json, &token);
   1831    }
   1832 }
   1833 
   1834 /* Handle the "value" context */
   1835 static void json_process_value(lua_State *l, json_parse_t *json,
   1836                               json_token_t *token, bool use_luanil)
   1837 {
   1838    switch (token->type) {
   1839    case T_STRING:
   1840        lua_pushlstring(l, token->value.string, token->string_len);
   1841        break;;
   1842    case T_NUMBER:
   1843        lua_pushnumber(l, token->value.number);
   1844        break;;
   1845    case T_INTEGER:
   1846        lua_pushinteger(l, token->value.integer);
   1847        break;;
   1848    case T_BOOLEAN:
   1849        lua_pushboolean(l, token->value.boolean);
   1850        break;;
   1851    case T_OBJ_BEGIN:
   1852        json_parse_object_context(l, json);
   1853        break;;
   1854    case T_ARR_BEGIN:
   1855        json_parse_array_context(l, json);
   1856        break;;
   1857    case T_NULL:
   1858        if (use_luanil) {
   1859            lua_pushnil(l);
   1860        } else {
   1861            nlua_pushref(l, nlua_get_nil_ref(l));
   1862        }
   1863        break;;
   1864    default:
   1865        json_throw_parse_error(l, json, "value", token);
   1866    }
   1867 }
   1868 
   1869 static int json_decode(lua_State *l)
   1870 {
   1871    json_parse_t json;
   1872    json_token_t token;
   1873    json_options_t options = { .luanil_object = false, .luanil_array = false, .skip_comments = false };
   1874 
   1875    size_t json_len;
   1876 
   1877    switch (lua_gettop(l)) {
   1878    case 1:
   1879        break;
   1880    case 2:
   1881        luaL_checktype(l, 2, LUA_TTABLE);
   1882 
   1883        lua_getfield(l, 2, "skip_comments");
   1884        options.skip_comments = lua_toboolean(l, -1);
   1885        lua_pop(l, 1);
   1886 
   1887        lua_getfield(l, 2, "luanil");
   1888        if (lua_isnil(l, -1)) {
   1889            lua_pop(l, 1);
   1890            break;
   1891        }
   1892 
   1893        luaL_checktype(l, -1, LUA_TTABLE);
   1894 
   1895        lua_getfield(l, -1, "object");
   1896        options.luanil_object = lua_toboolean(l, -1);
   1897        lua_pop(l, 1);
   1898 
   1899        lua_getfield(l, -1, "array");
   1900        options.luanil_array = lua_toboolean(l, -1);
   1901        /* Also pop the luanil table */
   1902        lua_pop(l, 2);
   1903        break;
   1904    default:
   1905        return luaL_error (l, "expected 1 or 2 arguments");
   1906    }
   1907 
   1908    json.cfg = json_fetch_config(l);
   1909    json.data = luaL_checklstring(l, 1, &json_len);
   1910    json.options = &options;
   1911    json.current_depth = 0;
   1912    json.ptr = json.data;
   1913 
   1914    /* Detect Unicode other than UTF-8 (see RFC 4627, Sec 3)
   1915     *
   1916     * CJSON can support any simple data type, hence only the first
   1917     * character is guaranteed to be ASCII (at worst: '"'). This is
   1918     * still enough to detect whether the wrong encoding is in use. */
   1919    if (json_len >= 2 && (!json.data[0] || !json.data[1]))
   1920        luaL_error(l, "JSON parser does not support UTF-16 or UTF-32");
   1921 
   1922    /* Ensure the temporary buffer can hold the entire string.
   1923     * This means we no longer need to do length checks since the decoded
   1924     * string must be smaller than the entire json string */
   1925    json.tmp = strbuf_new(json_len);
   1926 
   1927    json_next_token(&json, &token);
   1928    json_process_value(l, &json, &token, json.options->luanil_object);
   1929 
   1930    /* Ensure there is no more input left */
   1931    json_next_token(&json, &token);
   1932 
   1933    if (token.type != T_END)
   1934        json_throw_parse_error(l, &json, "the end", &token);
   1935 
   1936    strbuf_free(json.tmp);
   1937 
   1938    return 1;
   1939 }
   1940 
   1941 /* ===== INITIALISATION ===== */
   1942 
   1943 #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
   1944 /* Compatibility for Lua 5.1 and older LuaJIT.
   1945 *
   1946 * compat_luaL_setfuncs() is used to create a module table where the functions
   1947 * have json_config_t as their first upvalue. Code borrowed from Lua 5.2
   1948 * source's luaL_setfuncs().
   1949 */
   1950 static void compat_luaL_setfuncs(lua_State *l, const luaL_Reg *reg, int nup)
   1951 {
   1952    int i;
   1953 
   1954    luaL_checkstack(l, nup, "too many upvalues");
   1955    for (; reg->name != NULL; reg++) {  /* fill the table with given functions */
   1956        for (i = 0; i < nup; i++)  /* copy upvalues to the top */
   1957            lua_pushvalue(l, -nup);
   1958        lua_pushcclosure(l, reg->func, nup);  /* closure with those upvalues */
   1959        lua_setfield(l, -(nup + 2), reg->name);
   1960    }
   1961    lua_pop(l, nup);  /* remove upvalues */
   1962 }
   1963 #else
   1964 #define compat_luaL_setfuncs(L, reg, nup) luaL_setfuncs(L, reg, nup)
   1965 #endif
   1966 
   1967 /* Call target function in protected mode with all supplied args.
   1968 * Assumes target function only returns a single non-nil value.
   1969 * Convert and return thrown errors as: nil, "error message" */
   1970 static int json_protect_conversion(lua_State *l)
   1971 {
   1972    int err;
   1973 
   1974    /* Deliberately throw an error for invalid arguments */
   1975    luaL_argcheck(l, lua_gettop(l) == 1, 1, "expected 1 argument");
   1976 
   1977    /* pcall() the function stored as upvalue(1) */
   1978    lua_pushvalue(l, lua_upvalueindex(1));
   1979    lua_insert(l, 1);
   1980    err = lua_pcall(l, 1, 1, 0);
   1981    if (!err)
   1982        return 1;
   1983 
   1984    if (err == LUA_ERRRUN) {
   1985        lua_pushnil(l);
   1986        lua_insert(l, -2);
   1987        return 2;
   1988    }
   1989 
   1990    /* Since we are not using a custom error handler, the only remaining
   1991     * errors are memory related */
   1992    return luaL_error(l, "Memory allocation error in CJSON protected call");
   1993 }
   1994 
   1995 /* Return cjson module table */
   1996 int lua_cjson_new(lua_State *l)
   1997 {
   1998    luaL_Reg reg[] = {
   1999        { "encode", json_encode },
   2000        { "decode", json_decode },
   2001        // Nvim: don't expose options which cause global side-effects.
   2002        /*
   2003        { "encode_empty_table_as_object", json_cfg_encode_empty_table_as_object },
   2004        { "decode_array_with_array_mt", json_cfg_decode_array_with_array_mt },
   2005        { "decode_skip_comments", json_cfg_decode_skip_comments },
   2006        { "encode_sparse_array", json_cfg_encode_sparse_array },
   2007        { "encode_max_depth", json_cfg_encode_max_depth },
   2008        { "decode_max_depth", json_cfg_decode_max_depth },
   2009        { "encode_number_precision", json_cfg_encode_number_precision },
   2010        { "encode_keep_buffer", json_cfg_encode_keep_buffer },
   2011        { "encode_invalid_numbers", json_cfg_encode_invalid_numbers },
   2012        { "decode_invalid_numbers", json_cfg_decode_invalid_numbers },
   2013        { "encode_escape_forward_slash", json_cfg_encode_escape_forward_slash },
   2014        { "encode_skip_unsupported_value_types", json_cfg_encode_skip_unsupported_value_types },
   2015        { "encode_indent", json_cfg_encode_indent },
   2016        { "encode_sort_keys", json_cfg_encode_sort_keys },
   2017        */
   2018        { "new", lua_cjson_new },
   2019        { NULL, NULL }
   2020    };
   2021 
   2022    /* Initialise number conversions */
   2023    lua_getfield(l, LUA_REGISTRYINDEX, "nvim.thread");
   2024    bool is_thread = lua_toboolean(l, -1);
   2025    lua_pop(l, 1);
   2026 
   2027    // Since fpconv_init does not need to be called multiple times and is not
   2028    // thread safe, it should only be called in the main thread.
   2029    if (!is_thread) {
   2030        fpconv_init();
   2031    }
   2032 
   2033    /* Test if array metatables are in registry */
   2034    lua_pushlightuserdata(l, json_lightudata_mask(&json_empty_array));
   2035    lua_rawget(l, LUA_REGISTRYINDEX);
   2036    if (lua_isnil(l, -1)) {
   2037        /* Create array metatables.
   2038         *
   2039         * If multiple calls to lua_cjson_new() are made,
   2040         * this prevents overriding the tables at the given
   2041         * registry's index with a new one.
   2042         */
   2043        lua_pop(l, 1);
   2044 
   2045        /* empty_array_mt */
   2046        lua_pushlightuserdata(l, json_lightudata_mask(&json_empty_array));
   2047        lua_newtable(l);
   2048        lua_rawset(l, LUA_REGISTRYINDEX);
   2049 
   2050        /* array_mt */
   2051        lua_pushlightuserdata(l, json_lightudata_mask(&json_array));
   2052        lua_newtable(l);
   2053        lua_rawset(l, LUA_REGISTRYINDEX);
   2054    }
   2055 
   2056    /* cjson module table */
   2057    lua_newtable(l);
   2058 
   2059    /* Register functions with config data as upvalue */
   2060    json_create_config(l);
   2061    compat_luaL_setfuncs(l, reg, 1);
   2062 
   2063    // Nvim: don't expose "null", it is identical to vim.NIL.
   2064    /*
   2065    nlua_pushref(l, nlua_get_nil_ref(l));
   2066    lua_setfield(l, -2, "null");
   2067    */
   2068 
   2069    // Nvim: don't expose empty_array_mt.
   2070    /*
   2071    lua_pushlightuserdata(l, json_lightudata_mask(&json_empty_array));
   2072    lua_rawget(l, LUA_REGISTRYINDEX);
   2073    lua_setfield(l, -2, "empty_array_mt");
   2074    */
   2075 
   2076    // Nvim: don't expose array_mt.
   2077    /*
   2078    lua_pushlightuserdata(l, json_lightudata_mask(&json_array));
   2079    lua_rawget(l, LUA_REGISTRYINDEX);
   2080    lua_setfield(l, -2, "array_mt");
   2081    */
   2082 
   2083    // Nvim: don't expose empty_array.
   2084    /*
   2085    lua_pushlightuserdata(l, json_lightudata_mask(&json_array));
   2086    lua_setfield(l, -2, "empty_array");
   2087    */
   2088 
   2089    /* Set module name / version fields */
   2090    lua_pushliteral(l, CJSON_MODNAME);
   2091    lua_setfield(l, -2, "_NAME");
   2092    lua_pushliteral(l, CJSON_VERSION);
   2093    lua_setfield(l, -2, "_VERSION");
   2094 
   2095    return 1;
   2096 }
   2097 
   2098 /* Return cjson.safe module table */
   2099 static int lua_cjson_safe_new(lua_State *l)
   2100 {
   2101    const char *func[] = { "decode", "encode", NULL };
   2102    int i;
   2103 
   2104    lua_cjson_new(l);
   2105 
   2106    /* Fix new() method */
   2107    lua_pushcfunction(l, lua_cjson_safe_new);
   2108    lua_setfield(l, -2, "new");
   2109 
   2110    for (i = 0; func[i]; i++) {
   2111        lua_getfield(l, -1, func[i]);
   2112        lua_pushcclosure(l, json_protect_conversion, 1);
   2113        lua_setfield(l, -2, func[i]);
   2114    }
   2115 
   2116    return 1;
   2117 }
   2118 
   2119 int luaopen_cjson(lua_State *l)
   2120 {
   2121    lua_cjson_new(l);
   2122 
   2123 #ifdef ENABLE_CJSON_GLOBAL
   2124    /* Register a global "cjson" table. */
   2125    lua_pushvalue(l, -1);
   2126    lua_setglobal(l, CJSON_MODNAME);
   2127 #endif
   2128 
   2129    /* Return cjson table */
   2130    return 1;
   2131 }
   2132 
   2133 int luaopen_cjson_safe(lua_State *l)
   2134 {
   2135    lua_cjson_safe_new(l);
   2136 
   2137    /* Return cjson.safe table */
   2138    return 1;
   2139 }