robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
6b4ec2264e
master
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 117static const char * const * json_empty_array ; 118static const char * const * json_array ; 119 120typedef enum { 121T_OBJ_BEGIN , 122T_OBJ_END , 123T_ARR_BEGIN , 124T_ARR_END , 125T_STRING , 126T_NUMBER , 127T_INTEGER , 128T_BOOLEAN , 129T_NULL , 130T_COLON , 131T_COMMA , 132T_END , 133T_WHITESPACE , 134T_ERROR , 135T_UNKNOWN 136}json_token_type_t ; 137 138static 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" , 154NULL 155}; 156 157typedef struct { 158strbuf_t * buf ; 159size_t offset ; 160size_t length ; 161int raw_typ ; 162union { 163lua_Number number ; 164const 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*/ 174typedef struct { 175strbuf_t buf ; 176key_entry_t * keys ; 177size_t size ; 178size_t capacity ; 179}keybuf_t ; 180 181#define KEYBUF_DEFAULT_CAPACITY 32 182 183typedef struct { 184json_token_type_t ch2token [256 ]; 185char escape2char [256 ];/* Decoding */ 186 187/* encode_buf is only allocated and used when 188* encode_keep_buffer is set */ 189strbuf_t encode_buf ; 190 191/* encode_keybuf is only allocated and used when 192* sort_keys is set */ 193keybuf_t encode_keybuf ; 194 195int encode_sparse_convert ; 196int encode_sparse_ratio ; 197int encode_sparse_safe ; 198int encode_max_depth ; 199int encode_invalid_numbers ;/* 2 => Encode as "null" */ 200int encode_number_precision ; 201int encode_keep_buffer ; 202int encode_empty_table_as_object ; 203int encode_escape_forward_slash ; 204const char * encode_indent ; 205int encode_sort_keys ; 206 207int decode_invalid_numbers ; 208int decode_max_depth ; 209int decode_array_with_array_mt ; 210int decode_skip_comments ; 211int encode_skip_unsupported_value_types ; 212}json_config_t ; 213 214typedef struct { 215const char ** char2escape [256 ]; 216const char * indent ; 217int sort_keys ; 218 219/* keybuf is only allocated and used when 220* sort_keys is set */ 221keybuf_t keybuf ; 222}json_encode_options_t ; 223 224typedef struct { 225json_config_t * cfg ; 226json_encode_options_t * options ; 227strbuf_t * json ; 228}json_encode_t ; 229 230typedef struct { 231/* convert null in json objects to lua nil instead of vim.NIL */ 232bool luanil_object ; 233/* convert null in json arrays to lua nil instead of vim.NIL */ 234bool luanil_array ; 235bool skip_comments ; 236}json_options_t ; 237 238typedef struct { 239const char * data ; 240const char * ptr ; 241strbuf_t * tmp ;/* Temporary storage for strings */ 242json_config_t * cfg ; 243json_options_t * options ; 244int current_depth ; 245}json_parse_t ; 246 247typedef struct { 248json_token_type_t type ; 249size_t index ; 250union { 251const char * string ; 252double number ; 253lua_Integer integer ; 254int boolean ; 255 }value ; 256size_t string_len ; 257}json_token_t ; 258 259static 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" , 268NULL ,NULL ,"\\\"" ,NULL ,NULL ,NULL ,NULL ,NULL , 269NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 270NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 271NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 272NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 273NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 274NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 275NULL ,NULL ,NULL ,NULL ,"\\\\" ,NULL ,NULL ,NULL , 276NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 277NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 278NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 279NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,"\\u007f" , 280NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 281NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 282NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 283NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 284NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 285NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 286NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 287NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 288NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 289NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 290NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 291NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 292NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 293NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 294NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 295NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL ,NULL , 296}; 297 298/* ===== CONFIGURATION ===== */ 299 300static json_config_t * json_fetch_config (lua_State * l ) 301{ 302json_config_t * cfg ; 303 304cfg = (json_config_t * )lua_touserdata (l ,lua_upvalueindex (1 )); 305if (!cfg ) 306luaL_error (l ,"BUG: Unable to fetch CJSON configuration" ); 307 308return 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/* 315static json_config_t *json_arg_init(lua_State *l, int args) 316{ 317luaL_argcheck(l, lua_gettop(l) <= args, args + 1, 318"found too many arguments"); 319 320while (lua_gettop(l) < args) 321lua_pushnil(l); 322 323return json_fetch_config(l); 324} 325*/ 326 327/* Process integer options for configuration functions */ 328/* 329static int json_integer_option(lua_State *l, int optindex, int *setting, 330int min, int max) 331{ 332char errmsg[64]; 333int value; 334 335if (!lua_isnil(l, optindex)) { 336value = luaL_checkinteger(l, optindex); 337snprintf(errmsg, sizeof(errmsg), "expected integer between %d and %d", min, max); 338luaL_argcheck(l, min <= value && value <= max, 1, errmsg); 339*setting = value; 340} 341 342lua_pushinteger(l, *setting); 343 344return 1; 345} 346*/ 347 348/* Process enumerated arguments for a configuration function */ 349/* 350static int json_enum_option(lua_State *l, int optindex, int *setting, 351const char **options, int bool_true) 352{ 353static const char *bool_options[] = { "off", "on", NULL }; 354 355if (!options) { 356options = bool_options; 357bool_true = 1; 358} 359 360if (!lua_isnil(l, optindex)) { 361if (bool_true && lua_isboolean(l, optindex)) 362*setting = lua_toboolean(l, optindex) * bool_true; 363else 364*setting = luaL_checkoption(l, optindex, NULL, options); 365} 366 367if (bool_true && (*setting == 0 || *setting == bool_true)) 368lua_pushboolean(l, *setting); 369else 370lua_pushstring(l, options[*setting]); 371 372return 1; 373} 374*/ 375 376/* Process string option for a configuration function */ 377/* 378static int json_string_option(lua_State *l, int optindex, const char **setting) 379{ 380if (!lua_isnil(l, optindex)) { 381const char *value = luaL_checkstring(l, optindex); 382*setting = value; 383} 384 385lua_pushstring(l, *setting ? *setting : ""); 386return 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/* 395static int json_cfg_encode_sparse_array(lua_State *l) 396{ 397json_config_t *cfg = json_arg_init(l, 3); 398 399json_enum_option(l, 1, &cfg->encode_sparse_convert, NULL, 1); 400json_integer_option(l, 2, &cfg->encode_sparse_ratio, 0, INT_MAX); 401json_integer_option(l, 3, &cfg->encode_sparse_safe, 0, INT_MAX); 402 403return 3; 404} 405*/ 406 407/* Configures the maximum number of nested arrays/objects allowed when 408* encoding */ 409/* 410static int json_cfg_encode_max_depth(lua_State *l) 411{ 412json_config_t *cfg = json_arg_init(l, 1); 413 414return 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/* 421static int json_cfg_decode_max_depth(lua_State *l) 422{ 423json_config_t *cfg = json_arg_init(l, 1); 424 425return 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/* 431static int json_cfg_encode_number_precision(lua_State *l) 432{ 433json_config_t *cfg = json_arg_init(l, 1); 434 435return 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/* 441static int json_cfg_encode_empty_table_as_object(lua_State *l) 442{ 443json_config_t *cfg = json_arg_init(l, 1); 444 445return json_enum_option(l, 1, &cfg->encode_empty_table_as_object, NULL, 1); 446} 447*/ 448 449/* Configures how to decode arrays */ 450/* 451static int json_cfg_decode_array_with_array_mt(lua_State *l) 452{ 453json_config_t *cfg = json_arg_init(l, 1); 454 455json_enum_option(l, 1, &cfg->decode_array_with_array_mt, NULL, 1); 456 457return 1; 458} 459*/ 460 461/* Configures whether decoder should skip comments */ 462/* 463static int json_cfg_decode_skip_comments(lua_State *l) 464{ 465json_config_t *cfg = json_arg_init(l, 1); 466 467json_enum_option(l, 1, &cfg->decode_skip_comments, NULL, 1); 468 469return 1; 470} 471*/ 472 473/* Configure how to treat invalid types */ 474/* 475static int json_cfg_encode_skip_unsupported_value_types(lua_State *l) 476{ 477json_config_t *cfg = json_arg_init(l, 1); 478 479json_enum_option(l, 1, &cfg->encode_skip_unsupported_value_types, NULL, 1); 480 481return 1; 482} 483*/ 484 485/* Configures JSON encoding buffer persistence */ 486/* 487static int json_cfg_encode_keep_buffer(lua_State *l) 488{ 489json_config_t *cfg = json_arg_init(l, 1); 490int old_value; 491 492old_value = cfg->encode_keep_buffer; 493 494json_enum_option(l, 1, &cfg->encode_keep_buffer, NULL, 1); 495 496// Init / free the buffer if the setting has changed 497if (old_value ^ cfg->encode_keep_buffer) { 498if (cfg->encode_keep_buffer) 499strbuf_init(&cfg->encode_buf, 0); 500else 501strbuf_free(&cfg->encode_buf); 502} 503 504return 1; 505} 506*/ 507 508/* Configure how to indent output */ 509/* 510static int json_cfg_encode_indent(lua_State *l) 511{ 512json_config_t *cfg = json_arg_init(l, 1); 513 514json_string_option(l, 1, &cfg->encode_indent); 515// simplify further checking 516if (cfg->encode_indent[0] == '\0') cfg->encode_indent = NULL; 517 518return 1; 519} 520*/ 521 522#if defined(DISABLE_INVALID_NUMBERS )&& !defined(USE_INTERNAL_FPCONV ) 523void json_verify_invalid_number_setting (lua_State * l ,int * setting ) 524{ 525if (* setting == 1 ) { 526* setting = 0 ; 527luaL_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/* 535static int json_cfg_encode_invalid_numbers(lua_State *l) 536{ 537static const char *options[] = { "off", "on", "null", NULL }; 538json_config_t *cfg = json_arg_init(l, 1); 539 540json_enum_option(l, 1, &cfg->encode_invalid_numbers, options, 1); 541 542json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers); 543 544return 1; 545} 546*/ 547 548/* 549static int json_cfg_decode_invalid_numbers(lua_State *l) 550{ 551json_config_t *cfg = json_arg_init(l, 1); 552 553json_enum_option(l, 1, &cfg->decode_invalid_numbers, NULL, 1); 554 555json_verify_invalid_number_setting(l, &cfg->encode_invalid_numbers); 556 557return 1; 558} 559*/ 560 561/* 562static int json_cfg_encode_escape_forward_slash(lua_State *l) 563{ 564int ret; 565json_config_t *cfg = json_arg_init(l, 1); 566 567ret = json_enum_option(l, 1, &cfg->encode_escape_forward_slash, NULL, 1); 568if (cfg->encode_escape_forward_slash) { 569char2escape['/'] = "\\/"; 570} else { 571char2escape['/'] = NULL; 572} 573return ret; 574} 575*/ 576 577/* 578static int json_cfg_encode_sort_keys(lua_State *l) 579{ 580json_config_t *cfg = json_arg_init(l, 1); 581 582json_enum_option(l, 1, &cfg->encode_sort_keys, NULL, 1); 583 584return 1; 585} 586*/ 587 588static int json_destroy_config (lua_State * l ) 589{ 590json_config_t * cfg ; 591 592cfg = (json_config_t * )lua_touserdata (l ,1 ); 593if (cfg ) 594strbuf_free (& cfg -> encode_buf ); 595cfg = NULL ; 596 597return 0 ; 598} 599 600static void json_create_config (lua_State * l ) 601{ 602json_config_t * cfg ; 603int i ; 604 605cfg = (json_config_t * )lua_newuserdata (l ,sizeof (* cfg )); 606if (!cfg ) 607abort (); 608 609memset (cfg ,0 ,sizeof (* cfg )); 610 611/* Create GC method to clean up strbuf */ 612lua_newtable (l ); 613lua_pushcfunction (l ,json_destroy_config ); 614lua_setfield (l ,-2 ,"__gc" ); 615lua_setmetatable (l ,-2 ); 616 617cfg -> encode_sparse_convert = DEFAULT_SPARSE_CONVERT ; 618cfg -> encode_sparse_ratio = DEFAULT_SPARSE_RATIO ; 619cfg -> encode_sparse_safe = DEFAULT_SPARSE_SAFE ; 620cfg -> encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH ; 621cfg -> decode_max_depth = DEFAULT_DECODE_MAX_DEPTH ; 622cfg -> encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS ; 623cfg -> decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS ; 624cfg -> encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER ; 625cfg -> encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION ; 626cfg -> encode_empty_table_as_object = DEFAULT_ENCODE_EMPTY_TABLE_AS_OBJECT ; 627cfg -> decode_array_with_array_mt = DEFAULT_DECODE_ARRAY_WITH_ARRAY_MT ; 628cfg -> decode_skip_comments = DEFAULT_DECODE_SKIP_COMMENTS ; 629cfg -> encode_escape_forward_slash = DEFAULT_ENCODE_ESCAPE_FORWARD_SLASH ; 630cfg -> encode_skip_unsupported_value_types = DEFAULT_ENCODE_SKIP_UNSUPPORTED_VALUE_TYPES ; 631cfg -> encode_indent = DEFAULT_ENCODE_INDENT ; 632cfg -> encode_sort_keys = DEFAULT_ENCODE_SORT_KEYS ; 633 634#if DEFAULT_ENCODE_KEEP_BUFFER > 0 635strbuf_init (& cfg -> encode_buf ,0 ); 636#endif 637 638/* Decoding init */ 639 640/* Tag all characters as an error */ 641for (i = 0 ;i < 256 ;i ++ ) 642cfg -> ch2token [i ]= T_ERROR ; 643 644/* Set tokens that require no further processing */ 645cfg -> ch2token ['{' ]= T_OBJ_BEGIN ; 646cfg -> ch2token ['}' ]= T_OBJ_END ; 647cfg -> ch2token ['[' ]= T_ARR_BEGIN ; 648cfg -> ch2token [']' ]= T_ARR_END ; 649cfg -> ch2token [',' ]= T_COMMA ; 650cfg -> ch2token [':' ]= T_COLON ; 651cfg -> ch2token ['\0' ]= T_END ; 652cfg -> ch2token [' ' ]= T_WHITESPACE ; 653cfg -> ch2token ['\t' ]= T_WHITESPACE ; 654cfg -> ch2token ['\n' ]= T_WHITESPACE ; 655cfg -> ch2token ['\r' ]= T_WHITESPACE ; 656 657/* Update characters that require further processing */ 658cfg -> ch2token ['f' ]= T_UNKNOWN ;/* false? */ 659cfg -> ch2token ['i' ]= T_UNKNOWN ;/* inf, infinity? */ 660cfg -> ch2token ['I' ]= T_UNKNOWN ; 661cfg -> ch2token ['n' ]= T_UNKNOWN ;/* null, nan? */ 662cfg -> ch2token ['N' ]= T_UNKNOWN ; 663cfg -> ch2token ['t' ]= T_UNKNOWN ;/* true? */ 664cfg -> ch2token ['"' ]= T_UNKNOWN ;/* string? */ 665cfg -> ch2token ['+' ]= T_UNKNOWN ;/* number? */ 666cfg -> ch2token ['-' ]= T_UNKNOWN ; 667for (i = 0 ;i < 10 ;i ++ ) 668cfg -> ch2token ['0' + i ]= T_UNKNOWN ; 669 670/* Lookup table for parsing escape characters */ 671for (i = 0 ;i < 256 ;i ++ ) 672cfg -> escape2char [i ]= 0 ;/* String error */ 673cfg -> escape2char ['"' ]= '"' ; 674cfg -> escape2char ['\\' ]= '\\' ; 675cfg -> escape2char ['/' ]= '/' ; 676cfg -> escape2char ['b' ]= '\b' ; 677cfg -> escape2char ['t' ]= '\t' ; 678cfg -> escape2char ['n' ]= '\n' ; 679cfg -> escape2char ['f' ]= '\f' ; 680cfg -> escape2char ['r' ]= '\r' ; 681cfg -> escape2char ['u' ]= 'u' ;/* Unicode parsing required */ 682} 683 684/* ===== ENCODING ===== */ 685 686static void json_encode_exception (lua_State * l ,json_encode_t * ctx ,int lindex , 687const char * reason ) 688{ 689if (!ctx -> cfg -> encode_keep_buffer ) 690strbuf_free (ctx -> json ); 691 692if (ctx -> options -> sort_keys ) { 693strbuf_free (& ctx -> options -> keybuf .buf ); 694free (ctx -> options -> keybuf .keys ); 695 } 696 697luaL_error (l ,"Cannot serialise %s: %s" , 698lua_typename (l ,lua_type (l ,lindex )),reason ); 699} 700 701static void json_append_string_contents (lua_State * l ,json_encode_t * ctx , 702int lindex ,int use_keybuf ) 703{ 704const char * escstr ; 705const char * str ; 706size_t len ; 707size_t i ; 708strbuf_t * json = ctx -> json ; 709if (use_keybuf ) { 710json = & ctx -> options -> keybuf .buf ; 711 } 712 713str = 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. */ 719if (len >=SIZE_MAX /6 ) 720abort ();/* Overflow check */ 721strbuf_ensure_empty_length (json ,len * 6 ); 722 723for (i = 0 ;i < len ;i ++ ) { 724escstr = (* ctx -> options -> char2escape )[(unsigned char )str [i ]]; 725if (escstr ) 726strbuf_append_string (json ,escstr ); 727else 728strbuf_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 */ 738static void json_append_string (lua_State * l ,json_encode_t * ctx ,int lindex ) 739{ 740strbuf_append_char (ctx -> json ,'\"' ); 741json_append_string_contents (l ,ctx ,lindex , false); 742strbuf_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*/ 749static int lua_array_length (lua_State * l ,json_encode_t * ctx ) 750{ 751double k ; 752int max ; 753int items ; 754json_config_t * cfg = ctx -> cfg ; 755 756max = 0 ; 757items = 0 ; 758 759lua_pushnil (l ); 760/* table, startkey */ 761while (lua_next (l ,-2 )!= 0 ) { 762/* table, key, value */ 763if (lua_type (l ,-2 )== LUA_TNUMBER && 764 (k = lua_tonumber (l ,-2 ))) { 765/* Integer >= 1 ? */ 766if (floor (k )== k && k >=1 ) { 767if (k > max ) 768max = k ; 769items ++ ; 770lua_pop (l ,1 ); 771continue ; 772 } 773 } 774 775/* Must not be an array (non integer key) */ 776lua_pop (l ,2 ); 777return -1 ; 778 } 779 780/* Encode excessively sparse arrays as objects (if enabled) */ 781if (cfg -> encode_sparse_ratio > 0 && 782max > items * cfg -> encode_sparse_ratio && 783max > cfg -> encode_sparse_safe ) { 784if (!cfg -> encode_sparse_convert ) 785json_encode_exception (l ,ctx ,-1 ,"excessively sparse array" ); 786 787return -1 ; 788 } 789 790return max ; 791} 792 793static void json_check_encode_depth (lua_State * l ,json_config_t * cfg , 794int 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. */ 806if (current_depth <=cfg -> encode_max_depth && lua_checkstack (l ,3 )) 807return ; 808 809if (!cfg -> encode_keep_buffer ) 810strbuf_free (json ); 811 812luaL_error (l ,"Cannot serialise, excessive nesting (%d)" , 813current_depth ); 814} 815 816static int json_append_data (lua_State * l ,json_encode_t * cfg , 817int current_depth ); 818 819static void json_append_newline_and_indent (strbuf_t * json ,json_encode_t * ctx ,int depth ) 820{ 821strbuf_append_char (json ,'\n' ); 822for (int i = 0 ;i < depth ;i ++ ) 823strbuf_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) */ 830static void json_append_array (lua_State * l ,json_encode_t * ctx ,int current_depth , 831int array_length ,int raw ) 832{ 833int comma ,i ,json_pos ,err ; 834int has_items = 0 ; 835strbuf_t * json = ctx -> json ; 836 837strbuf_append_char (json ,'[' ); 838 839comma = 0 ; 840for (i = 1 ;i <=array_length ;i ++ ) { 841has_items = 1 ; 842 843json_pos = strbuf_length (json ); 844if (comma ++ > 0 ) 845strbuf_append_char (json ,',' ); 846 847if (ctx -> options -> indent ) 848json_append_newline_and_indent (json ,ctx ,current_depth ); 849 850if (raw ) { 851lua_rawgeti (l ,-1 ,i ); 852 }else { 853#if LUA_VERSION_NUM >=503 854lua_geti (l ,-1 ,i ); 855#else 856lua_pushinteger (l ,i ); 857lua_gettable (l ,-2 ); 858#endif 859 } 860 861err = json_append_data (l ,ctx ,current_depth ); 862if (err ) { 863strbuf_set_length (json ,json_pos ); 864if (comma == 1 ) { 865comma = 0 ; 866 } 867 } 868lua_pop (l ,1 ); 869 } 870 871if (has_items && ctx -> options -> indent ) 872json_append_newline_and_indent (json ,ctx ,current_depth - 1 ); 873 874strbuf_append_char (json ,']' ); 875} 876 877static void json_append_number (lua_State * l ,json_encode_t * ctx , 878int lindex ,int use_keybuf ) 879{ 880int len ; 881#if LUA_VERSION_NUM >=503 882if (lua_isinteger (l ,lindex )) { 883lua_Integer num = lua_tointeger (l ,lindex ); 884strbuf_ensure_empty_length (json ,FPCONV_G_FMT_BUFSIZE );/* max length of int64 is 19 */ 885len = sprintf (strbuf_empty_ptr (json ),LUA_INTEGER_FMT ,num ); 886strbuf_extend_length (json ,len ); 887return ; 888 } 889#endif 890double num = lua_tonumber (l ,lindex ); 891json_config_t * cfg = ctx -> cfg ; 892strbuf_t * json = ctx -> json ; 893if (use_keybuf ) { 894json = & ctx -> options -> keybuf .buf ; 895 } 896 897if (cfg -> encode_invalid_numbers == 0 ) { 898/* Prevent encoding invalid numbers */ 899if (isinf (num )|| isnan (num )) 900json_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. */ 905if (isnan (num )) { 906strbuf_append_mem (json ,"NaN" ,3 ); 907return ; 908 } 909if (isinf (num )) { 910if (num < 0 ) 911strbuf_append_mem (json ,"-Infinity" ,9 ); 912else 913strbuf_append_mem (json ,"Infinity" ,8 ); 914return ; 915 } 916 }else { 917/* Encode invalid numbers as "null" */ 918if (isinf (num )|| isnan (num )) { 919strbuf_append_mem (json ,"null" ,4 ); 920return ; 921 } 922 } 923 924strbuf_ensure_empty_length (json ,FPCONV_G_FMT_BUFSIZE ); 925len = fpconv_g_fmt (strbuf_empty_ptr (json ),num ,cfg -> encode_number_precision ); 926strbuf_extend_length (json ,len ); 927} 928 929/* Compare key_entry_t for qsort. */ 930static int cmp_key_entries (const void * a ,const void * b ) { 931const key_entry_t * ka = a ; 932const key_entry_t * kb = b ; 933int res = memcmp (ka -> buf -> buf + ka -> offset , 934kb -> buf -> buf + kb -> offset , 935ka -> length < kb -> length ?ka -> length :kb -> length ); 936if (res == 0 ) 937return (ka -> length - kb -> length ); 938return res ; 939} 940 941static void json_append_object (lua_State * l ,json_encode_t * ctx , 942int current_depth ) 943{ 944int comma ,keytype ,json_pos ,err ; 945int has_items = 0 ; 946strbuf_t * json = ctx -> json ; 947 948/* Object */ 949strbuf_append_char (json ,'{' ); 950 951comma = 0 ; 952lua_pushnil (l ); 953if (ctx -> options -> sort_keys ) { 954keybuf_t * keybuf = & ctx -> options -> keybuf ; 955size_t init_keybuf_size = keybuf -> size ; 956size_t init_keybuf_length = strbuf_length (& keybuf -> buf ); 957 958while (lua_next (l ,-2 )!= 0 ) { 959has_items = 1 ; 960if (keybuf -> size == keybuf -> capacity ) { 961keybuf -> capacity *=2 ; 962key_entry_t * tmp = realloc (keybuf -> keys , 963keybuf -> capacity * sizeof (key_entry_t )); 964if (!tmp ) 965json_encode_exception (l ,ctx ,-1 ,"out of memory" ); 966keybuf -> keys = tmp ; 967 } 968 969keytype = lua_type (l ,-2 ); 970key_entry_t key_entry = { 971 .buf = & keybuf -> buf , 972 .offset = strbuf_length (& keybuf -> buf ), 973 .raw_typ = keytype , 974 }; 975if (keytype == LUA_TSTRING ) { 976json_append_string_contents (l ,ctx ,-2 , true); 977key_entry .raw .string = lua_tostring (l ,-2 ); 978 }else if (keytype == LUA_TNUMBER ) { 979json_append_number (l ,ctx ,-2 , true); 980key_entry .raw .number = lua_tointeger (l ,-2 ); 981 }else { 982json_encode_exception (l ,ctx ,-2 , 983"table key must be number or string" ); 984 } 985key_entry .length = strbuf_length (& keybuf -> buf )- key_entry .offset ; 986keybuf -> keys [keybuf -> size ++ ]= key_entry ; 987lua_pop (l ,1 ); 988 } 989 990size_t keys_count = keybuf -> size - init_keybuf_size ; 991qsort (keybuf -> keys + init_keybuf_size ,keys_count , 992sizeof (key_entry_t ),cmp_key_entries ); 993 994for (size_t i = init_keybuf_size ;i < init_keybuf_size + keys_count ;i ++ ) { 995key_entry_t * current_key = & keybuf -> keys [i ]; 996json_pos = strbuf_length (json ); 997if (comma ++ > 0 ) 998strbuf_append_char (json ,',' ); 999 1000if (ctx -> options -> indent ) 1001json_append_newline_and_indent (json ,ctx ,current_depth ); 1002 1003strbuf_ensure_empty_length (json ,current_key -> length + 3 ); 1004strbuf_append_char_unsafe (json ,'"' ); 1005strbuf_append_mem_unsafe (json ,keybuf -> buf .buf + current_key -> offset , 1006current_key -> length ); 1007strbuf_append_mem_unsafe (json ,"\":" ,2 ); 1008 1009if (ctx -> options -> indent ) 1010strbuf_append_char (json ,' ' ); 1011 1012if (current_key -> raw_typ == LUA_TSTRING ) 1013lua_pushstring (l ,current_key -> raw .string ); 1014else 1015lua_pushnumber (l ,current_key -> raw .number ); 1016 1017lua_gettable (l ,-2 ); 1018err = json_append_data (l ,ctx ,current_depth ); 1019if (err ) { 1020strbuf_set_length (json ,json_pos ); 1021if (comma == 1 ) 1022comma = 0 ; 1023 } 1024lua_pop (l ,1 ); 1025 } 1026/* resize encode_keybuf to reuse allocated memory for forward keys */ 1027strbuf_set_length (& keybuf -> buf ,init_keybuf_length ); 1028keybuf -> size = init_keybuf_size ; 1029 }else { 1030while (lua_next (l ,-2 )!= 0 ) { 1031has_items = 1 ; 1032 1033json_pos = strbuf_length (json ); 1034if (comma ++ > 0 ) 1035strbuf_append_char (json ,',' ); 1036 1037if (ctx -> options -> indent ) 1038json_append_newline_and_indent (json ,ctx ,current_depth ); 1039 1040/* table, key, value */ 1041keytype = lua_type (l ,-2 ); 1042if (keytype == LUA_TNUMBER ) { 1043strbuf_append_char (json ,'"' ); 1044json_append_number (l ,ctx ,-2 , false); 1045strbuf_append_mem (json ,"\":" ,2 ); 1046 }else if (keytype == LUA_TSTRING ) { 1047json_append_string (l ,ctx ,-2 ); 1048strbuf_append_char (json ,':' ); 1049 }else { 1050json_encode_exception (l ,ctx ,-2 , 1051"table key must be a number or string" ); 1052/* never returns */ 1053 } 1054if (ctx -> options -> indent ) 1055strbuf_append_char (json ,' ' ); 1056 1057/* table, key, value */ 1058err = json_append_data (l ,ctx ,current_depth ); 1059if (err ) { 1060strbuf_set_length (json ,json_pos ); 1061if (comma == 1 ) 1062comma = 0 ; 1063 } 1064 1065lua_pop (l ,1 ); 1066/* table, key */ 1067 } 1068 } 1069 1070if (has_items && ctx -> options -> indent ) 1071json_append_newline_and_indent (json ,ctx ,current_depth - 1 ); 1072 1073strbuf_append_char (json ,'}' ); 1074} 1075 1076/* Serialise Lua data into JSON string. Return 1 if an error happened, else 0. */ 1077static int json_append_data (lua_State * l ,json_encode_t * ctx , 1078int current_depth ) 1079{ 1080int len ; 1081int as_array = 0 ; 1082int as_empty_dict = 0 ; 1083int has_metatable ; 1084int raw = 1 ; 1085json_config_t * cfg = ctx -> cfg ; 1086strbuf_t * json = ctx -> json ; 1087 1088switch (lua_type (l ,-1 )) { 1089case LUA_TSTRING : 1090json_append_string (l ,ctx ,-1 ); 1091break ; 1092case LUA_TNUMBER : 1093json_append_number (l ,ctx ,-1 , false); 1094break ; 1095case LUA_TBOOLEAN : 1096if (lua_toboolean (l ,-1 )) 1097strbuf_append_mem (json ,"true" ,4 ); 1098else 1099strbuf_append_mem (json ,"false" ,5 ); 1100break ; 1101case LUA_TTABLE : 1102current_depth ++ ; 1103json_check_encode_depth (l ,cfg ,current_depth ,json ); 1104 1105has_metatable = lua_getmetatable (l ,-1 ); 1106 1107if (has_metatable ) { 1108 1109nlua_pushref (l ,nlua_get_empty_dict_ref (l )); 1110if (lua_rawequal (l ,-2 ,-1 )) { 1111as_empty_dict = true; 1112 }else { 1113lua_pop (l ,1 ); 1114lua_pushlightuserdata (l ,json_lightudata_mask (& json_array )); 1115lua_rawget (l ,LUA_REGISTRYINDEX ); 1116as_array = lua_rawequal (l ,-1 ,-2 ); 1117 } 1118if (as_array ) { 1119raw = 1 ; 1120lua_pop (l ,2 ); 1121len = lua_objlen (l ,-1 ); 1122 }else { 1123raw = 0 ; 1124lua_pop (l ,2 ); 1125if (luaL_getmetafield (l ,-1 ,"__len" )) { 1126lua_pushvalue (l ,-2 ); 1127lua_call (l ,1 ,1 ); 1128len = lua_tonumber (l ,-1 ); 1129lua_pop (l ,1 ); 1130as_array = 1 ; 1131 } 1132 } 1133 } 1134 1135if (as_array ) { 1136len = lua_objlen (l ,-1 ); 1137json_append_array (l ,ctx ,current_depth ,len ,raw ); 1138 }else { 1139len = lua_array_length (l ,ctx ); 1140 1141if (len > 0 || (len == 0 && !cfg -> encode_empty_table_as_object && !as_empty_dict )) { 1142json_append_array (l ,ctx ,current_depth ,len ,raw ); 1143 }else { 1144if (has_metatable ) { 1145lua_getmetatable (l ,-1 ); 1146lua_pushlightuserdata (l ,json_lightudata_mask ( 1147& json_empty_array )); 1148lua_rawget (l ,LUA_REGISTRYINDEX ); 1149as_array = lua_rawequal (l ,-1 ,-2 ); 1150lua_pop (l ,2 );/* pop pointer + metatable */ 1151if (as_array ) { 1152len = lua_objlen (l ,-1 ); 1153 1154raw = 1 ; 1155json_append_array (l ,ctx ,current_depth ,len ,raw ); 1156break ; 1157 } 1158 } 1159json_append_object (l ,ctx ,current_depth ); 1160 } 1161 } 1162break ; 1163case LUA_TNIL : 1164strbuf_append_mem (json ,"null" ,4 ); 1165break ; 1166case LUA_TLIGHTUSERDATA : 1167if (lua_touserdata (l ,-1 )== & json_array ) { 1168json_append_array (l ,ctx ,current_depth ,0 ,1 ); 1169 } 1170break ; 1171case LUA_TUSERDATA : 1172nlua_pushref (l ,nlua_get_nil_ref (l )); 1173bool is_nil = lua_rawequal (l ,-2 ,-1 ); 1174lua_pop (l ,1 ); 1175if (is_nil ) { 1176strbuf_append_mem (json ,"null" ,4 ); 1177break ; 1178 }else { 1179FALLTHROUGH ; 1180 } 1181default : 1182/* Remaining types (LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD, 1183* and LUA_TLIGHTUSERDATA) cannot be serialised */ 1184if (cfg -> encode_skip_unsupported_value_types ) { 1185return 1 ; 1186 }else { 1187json_encode_exception (l ,ctx ,-1 ,"type not supported" ); 1188 } 1189 1190/* never returns */ 1191 } 1192return 0 ; 1193} 1194 1195static int json_encode (lua_State * l ) 1196{ 1197json_config_t * cfg = json_fetch_config (l ); 1198json_encode_options_t options = { 1199 .char2escape = {char2escape }, 1200 .indent = DEFAULT_ENCODE_INDENT , 1201 .sort_keys = DEFAULT_ENCODE_SORT_KEYS , 1202 }; 1203json_encode_t ctx = { .options = & options , .cfg = cfg }; 1204strbuf_t local_encode_buf ; 1205strbuf_t * encode_buf ; 1206char * json ; 1207size_t len ; 1208const char * customChar2escape [256 ]; 1209 1210switch (lua_gettop (l )) { 1211case 1 : 1212break ; 1213case 2 : 1214luaL_checktype (l ,2 ,LUA_TTABLE ); 1215 1216lua_getfield (l ,2 ,"escape_slash" ); 1217if (!lua_isnil (l ,-1 )) { 1218luaL_checktype (l ,-1 ,LUA_TBOOLEAN ); 1219 1220int escape_slash = lua_toboolean (l ,-1 ); 1221if (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. */ 1224memcpy (customChar2escape ,char2escape ,sizeof (char2escape )); 1225customChar2escape ['/' ]= "\\/" ; 1226* ctx .options -> char2escape = customChar2escape ; 1227 } 1228 } 1229lua_pop (l ,1 ); 1230 1231lua_getfield (l ,2 ,"indent" ); 1232if (!lua_isnil (l ,-1 )) { 1233options .indent = luaL_checkstring (l ,-1 ); 1234if (options .indent [0 ]== '\0' )options .indent = NULL ; 1235 } 1236lua_pop (l ,1 ); 1237 1238lua_getfield (l ,2 ,"sort_keys" ); 1239if (!lua_isnil (l ,-1 )) { 1240luaL_checktype (l ,-1 ,LUA_TBOOLEAN ); 1241 1242int sort_keys = lua_toboolean (l ,-1 ); 1243if (sort_keys ) { 1244options .sort_keys = sort_keys ; 1245strbuf_init (& options .keybuf .buf ,0 ); 1246options .keybuf .size = 0 ; 1247options .keybuf .capacity = KEYBUF_DEFAULT_CAPACITY ; 1248options .keybuf .keys = malloc (options .keybuf .capacity * sizeof (key_entry_t )); 1249if (!options .keybuf .keys ) 1250return luaL_error (l ,"out of memory" ); 1251 } 1252 } 1253 1254/* Also pop the opts table */ 1255lua_pop (l ,2 ); 1256break ; 1257default : 1258return luaL_error (l ,"expected 1 or 2 arguments" ); 1259 } 1260 1261if (!cfg -> encode_keep_buffer ) { 1262/* Use private buffer */ 1263encode_buf = & local_encode_buf ; 1264strbuf_init (encode_buf ,0 ); 1265 }else { 1266/* Reuse existing buffer */ 1267encode_buf = & cfg -> encode_buf ; 1268strbuf_reset (encode_buf ); 1269 } 1270 1271ctx .json = encode_buf ; 1272json_append_data (l ,& ctx ,0 ); 1273json = strbuf_string (encode_buf ,& len ); 1274 1275lua_pushlstring (l ,json ,len ); 1276 1277if (!cfg -> encode_keep_buffer ) 1278strbuf_free (encode_buf ); 1279 1280if (options .sort_keys ) { 1281strbuf_free (& options .keybuf .buf ); 1282free (options .keybuf .keys ); 1283 } 1284 1285return 1 ; 1286} 1287 1288/* ===== DECODING ===== */ 1289 1290static void json_process_value (lua_State * l ,json_parse_t * json , 1291json_token_t * token ,bool use_luanil ); 1292 1293static int hexdigit2int (char hex ) 1294{ 1295if ('0' <=hex && hex <='9' ) 1296return hex - '0' ; 1297 1298/* Force lowercase */ 1299hex |=0x20 ; 1300if ('a' <=hex && hex <='f' ) 1301return 10 + hex - 'a' ; 1302 1303return -1 ; 1304} 1305 1306static int decode_hex4 (const char * hex ) 1307{ 1308int digit [4 ]; 1309int i ; 1310 1311/* Convert ASCII hex digit to numeric digit 1312* Note: this returns an error for invalid hex digits, including 1313* NULL */ 1314for (i = 0 ;i < 4 ;i ++ ) { 1315digit [i ]= hexdigit2int (hex [i ]); 1316if (digit [i ]< 0 ) { 1317return -1 ; 1318 } 1319 } 1320 1321return (digit [0 ] <<12 )+ 1322 (digit [1 ] <<8 )+ 1323 (digit [2 ] <<4 )+ 1324digit [3 ]; 1325} 1326 1327/* Converts a Unicode codepoint to UTF-8. 1328* Returns UTF-8 string length, and up to 4 bytes in *utf8 */ 1329static int codepoint_to_utf8 (char * utf8 ,int codepoint ) 1330{ 1331/* 0xxxxxxx */ 1332if (codepoint <=0x7F ) { 1333utf8 [0 ]= codepoint ; 1334return 1 ; 1335 } 1336 1337/* 110xxxxx 10xxxxxx */ 1338if (codepoint <=0x7FF ) { 1339utf8 [0 ]= (codepoint >>6 ) |0xC0 ; 1340utf8 [1 ]= (codepoint & 0x3F ) |0x80 ; 1341return 2 ; 1342 } 1343 1344/* 1110xxxx 10xxxxxx 10xxxxxx */ 1345if (codepoint <=0xFFFF ) { 1346utf8 [0 ]= (codepoint >>12 ) |0xE0 ; 1347utf8 [1 ]= ((codepoint >>6 )& 0x3F ) |0x80 ; 1348utf8 [2 ]= (codepoint & 0x3F ) |0x80 ; 1349return 3 ; 1350 } 1351 1352/* 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ 1353if (codepoint <=0x1FFFFF ) { 1354utf8 [0 ]= (codepoint >>18 ) |0xF0 ; 1355utf8 [1 ]= ((codepoint >>12 )& 0x3F ) |0x80 ; 1356utf8 [2 ]= ((codepoint >>6 )& 0x3F ) |0x80 ; 1357utf8 [3 ]= (codepoint & 0x3F ) |0x80 ; 1358return 4 ; 1359 } 1360 1361return 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*/ 1373static int json_append_unicode_escape (json_parse_t * json ) 1374{ 1375char utf8 [4 ];/* Surrogate pairs require 4 UTF-8 bytes */ 1376int codepoint ; 1377int surrogate_low ; 1378int len ; 1379int escape_len = 6 ; 1380 1381/* Fetch UTF-16 code unit */ 1382codepoint = decode_hex4 (json -> ptr + 2 ); 1383if (codepoint < 0 ) 1384return -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) */ 1392if ((codepoint & 0xF800 )== 0xD800 ) { 1393/* Error if the 1st surrogate is not high */ 1394if (codepoint & 0x400 ) 1395return -1 ; 1396 1397/* Ensure the next code is a unicode escape */ 1398if (* (json -> ptr + escape_len )!= '\\' || 1399* (json -> ptr + escape_len + 1 )!= 'u' ) { 1400return -1 ; 1401 } 1402 1403/* Fetch the next codepoint */ 1404surrogate_low = decode_hex4 (json -> ptr + 2 + escape_len ); 1405if (surrogate_low < 0 ) 1406return -1 ; 1407 1408/* Error if the 2nd code is not a low surrogate */ 1409if ((surrogate_low & 0xFC00 )!= 0xDC00 ) 1410return -1 ; 1411 1412/* Calculate Unicode codepoint */ 1413codepoint = (codepoint & 0x3FF ) <<10 ; 1414surrogate_low &=0x3FF ; 1415codepoint = (codepoint |surrogate_low )+ 0x10000 ; 1416escape_len = 12 ; 1417 } 1418 1419/* Convert codepoint to UTF-8 */ 1420len = codepoint_to_utf8 (utf8 ,codepoint ); 1421if (!len ) 1422return -1 ; 1423 1424/* Append bytes and advance parse index */ 1425strbuf_append_mem_unsafe (json -> tmp ,utf8 ,len ); 1426json -> ptr += escape_len ; 1427 1428return 0 ; 1429} 1430 1431static void json_set_token_error (json_token_t * token ,json_parse_t * json , 1432const char * errtype ) 1433{ 1434token -> type = T_ERROR ; 1435token -> index = json -> ptr - json -> data ; 1436token -> value .string = errtype ; 1437} 1438 1439static void json_next_string_token (json_parse_t * json ,json_token_t * token ) 1440{ 1441char * escape2char = json -> cfg -> escape2char ; 1442char ch ; 1443 1444/* Caller must ensure a string is next */ 1445assert (* json -> ptr == '"' ); 1446 1447/* Skip " */ 1448json -> 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*/ 1454strbuf_reset (json -> tmp ); 1455 1456while ((ch = * json -> ptr )!= '"' ) { 1457if (!ch ) { 1458/* Premature end of the string */ 1459json_set_token_error (token ,json ,"unexpected end of string" ); 1460return ; 1461 } 1462 1463/* Handle escapes */ 1464if (ch == '\\' ) { 1465/* Fetch escape character */ 1466ch = * (json -> ptr + 1 ); 1467 1468/* Translate escape code and append to tmp string */ 1469ch = escape2char [(unsigned char )ch ]; 1470if (ch == 'u' ) { 1471if (json_append_unicode_escape (json )== 0 ) 1472continue ; 1473 1474json_set_token_error (token ,json , 1475"invalid unicode escape code" ); 1476return ; 1477 } 1478if (!ch ) { 1479json_set_token_error (token ,json ,"invalid escape code" ); 1480return ; 1481 } 1482 1483/* Skip '\' */ 1484json -> ptr ++ ; 1485 } 1486/* Append normal character or translated single character 1487* Unicode escapes are handled above */ 1488strbuf_append_char_unsafe (json -> tmp ,ch ); 1489json -> ptr ++ ; 1490 } 1491json -> ptr ++ ;/* Eat final quote (") */ 1492 1493strbuf_ensure_null (json -> tmp ); 1494 1495token -> type = T_STRING ; 1496token -> 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*/ 1514static int json_is_invalid_number (json_parse_t * json ) 1515{ 1516const char * p = json -> ptr ; 1517 1518/* Reject numbers starting with + */ 1519if (* p == '+' ) 1520return 1 ; 1521 1522/* Skip minus sign if it exists */ 1523if (* p == '-' ) 1524p ++ ; 1525 1526/* Reject numbers starting with 0x, or leading zeros */ 1527if (* p == '0' ) { 1528char ch2 = * (p + 1 ); 1529 1530if ((ch2 |0x20 )== 'x' || /* Hex */ 1531 ('0' <=ch2 && ch2 <='9' ))/* Leading zero */ 1532return 1 ; 1533 1534return 0 ; 1535 }else if (* p <='9' ) { 1536return 0 ;/* Ordinary number */ 1537 } 1538 1539/* Reject inf/nan */ 1540if (!strncasecmp (p ,"inf" ,3 )) 1541return 1 ; 1542if (!strncasecmp (p ,"nan" ,3 )) 1543return 1 ; 1544 1545/* Pass all other numbers which may still be invalid, but 1546* strtod() will catch them. */ 1547return 0 ; 1548} 1549 1550static void json_next_number_token (json_parse_t * json ,json_token_t * token ) 1551{ 1552char * endptr ; 1553 1554long long tmpval = strtoll (json -> ptr ,& endptr ,10 ); 1555if (json -> ptr == endptr || * endptr == '.' || * endptr == 'e' || 1556* endptr == 'E' || * endptr == 'x' ) { 1557token -> type = T_NUMBER ; 1558token -> value .number = fpconv_strtod (json -> ptr ,& endptr ); 1559if (json -> ptr == endptr ) { 1560json_set_token_error (token ,json ,"invalid number" ); 1561return ; 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*/ 1568token -> type = T_NUMBER ; 1569token -> value .number = tmpval ; 1570 }else { 1571token -> type = T_INTEGER ; 1572token -> value .integer = tmpval ; 1573 } 1574json -> ptr = endptr ;/* Skip the processed number */ 1575 1576return ; 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*/ 1583static void json_next_token (json_parse_t * json ,json_token_t * token ) 1584{ 1585const json_token_type_t * ch2token = json -> cfg -> ch2token ; 1586int ch ; 1587 1588while (1 ) { 1589/* Eat whitespace. */ 1590while (1 ) { 1591ch = (unsigned char )* (json -> ptr ); 1592token -> type = ch2token [ch ]; 1593if (token -> type != T_WHITESPACE ) 1594break ; 1595json -> ptr ++ ; 1596 } 1597 1598if (!json -> options -> skip_comments ) 1599break ; 1600 1601/* Eat comments. */ 1602if ((unsigned char )json -> ptr [0 ]!= '/' || 1603 ((unsigned char )json -> ptr [1 ]!= '/' && 1604 (unsigned char )json -> ptr [1 ]!= '*' )) { 1605break ; 1606 } 1607 1608if (json -> ptr [1 ]== '/' ) { 1609/* Handle single-line comment */ 1610json -> ptr += 2 ; 1611while (* json -> ptr != '\0' && * json -> ptr != '\n' ) 1612json -> ptr ++ ; 1613 }else { 1614/* Handle multi-line comment */ 1615json -> ptr += 2 ; 1616while (1 ) { 1617if (* json -> ptr == '\0' ) { 1618json_set_token_error (token ,json ,"unclosed multi-line comment" ); 1619return ; 1620 } 1621if (json -> ptr [0 ]== '*' && json -> ptr [1 ]== '/' ) { 1622json -> ptr += 2 ; 1623break ; 1624 } 1625json -> ptr ++ ; 1626 } 1627 } 1628 } 1629 1630/* Store location of new token. Required when throwing errors 1631* for unexpected tokens (syntax errors). */ 1632token -> index = json -> ptr - json -> data ; 1633 1634/* Don't advance the pointer for an error or the end */ 1635if (token -> type == T_ERROR ) { 1636json_set_token_error (token ,json ,"invalid token" ); 1637return ; 1638 } 1639 1640if (token -> type == T_END ) { 1641return ; 1642 } 1643 1644/* Found a known single character token, advance index and return */ 1645if (token -> type != T_UNKNOWN ) { 1646json -> ptr ++ ; 1647return ; 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..) */ 1656if (ch == '"' ) { 1657json_next_string_token (json ,token ); 1658return ; 1659 }else if (ch == '-' || ('0' <=ch && ch <='9' )) { 1660if (!json -> cfg -> decode_invalid_numbers && json_is_invalid_number (json )) { 1661json_set_token_error (token ,json ,"invalid number" ); 1662return ; 1663 } 1664json_next_number_token (json ,token ); 1665return ; 1666 }else if (!strncmp (json -> ptr ,"true" ,4 )) { 1667token -> type = T_BOOLEAN ; 1668token -> value .boolean = 1 ; 1669json -> ptr += 4 ; 1670return ; 1671 }else if (!strncmp (json -> ptr ,"false" ,5 )) { 1672token -> type = T_BOOLEAN ; 1673token -> value .boolean = 0 ; 1674json -> ptr += 5 ; 1675return ; 1676 }else if (!strncmp (json -> ptr ,"null" ,4 )) { 1677token -> type = T_NULL ; 1678json -> ptr += 4 ; 1679return ; 1680 }else if (json -> cfg -> decode_invalid_numbers && 1681json_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*/ 1687json_next_number_token (json ,token ); 1688return ; 1689 } 1690 1691/* Token starts with t/f/n but isn't recognised above. */ 1692json_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 */ 1701static void json_throw_parse_error (lua_State * l ,json_parse_t * json , 1702const char * exp ,json_token_t * token ) 1703{ 1704const char * found ; 1705 1706strbuf_free (json -> tmp ); 1707 1708if (token -> type == T_ERROR ) 1709found = token -> value .string ; 1710else 1711found = json_token_type_name [token -> type ]; 1712 1713/* Note: token->index is 0 based, display starting from 1 */ 1714luaL_error (l ,"Expected %s but found %s at character %d" , 1715exp ,found ,token -> index + 1 ); 1716} 1717 1718static inline void json_decode_ascend (json_parse_t * json ) 1719{ 1720json -> current_depth -- ; 1721} 1722 1723static void json_decode_descend (lua_State * l ,json_parse_t * json ,int slots ) 1724{ 1725json -> current_depth ++ ; 1726 1727if (json -> current_depth <=json -> cfg -> decode_max_depth && 1728lua_checkstack (l ,slots )) { 1729return ; 1730 } 1731 1732strbuf_free (json -> tmp ); 1733luaL_error (l ,"Found too many nested data structures (%d) at character %d" , 1734json -> current_depth ,json -> ptr - json -> data ); 1735} 1736 1737static void json_parse_object_context (lua_State * l ,json_parse_t * json ) 1738{ 1739json_token_t token ; 1740 1741/* 3 slots required: 1742* .., table, key, value */ 1743json_decode_descend (l ,json ,3 ); 1744 1745lua_newtable (l ); 1746 1747json_next_token (json ,& token ); 1748 1749/* Handle empty objects */ 1750if (token .type == T_OBJ_END ) { 1751nlua_pushref (l ,nlua_get_empty_dict_ref (l )); \ 1752lua_setmetatable (l ,-2 ); \ 1753json_decode_ascend (json ); 1754return ; 1755 } 1756 1757while (1 ) { 1758if (token .type != T_STRING ) 1759json_throw_parse_error (l ,json ,"object key string" ,& token ); 1760 1761/* Push key */ 1762lua_pushlstring (l ,token .value .string ,token .string_len ); 1763 1764json_next_token (json ,& token ); 1765if (token .type != T_COLON ) 1766json_throw_parse_error (l ,json ,"colon" ,& token ); 1767 1768/* Fetch value */ 1769json_next_token (json ,& token ); 1770json_process_value (l ,json ,& token ,json -> options -> luanil_object ); 1771 1772/* Set key = value */ 1773lua_rawset (l ,-3 ); 1774 1775json_next_token (json ,& token ); 1776 1777if (token .type == T_OBJ_END ) { 1778json_decode_ascend (json ); 1779return ; 1780 } 1781 1782if (token .type != T_COMMA ) 1783json_throw_parse_error (l ,json ,"comma or object end" ,& token ); 1784 1785json_next_token (json ,& token ); 1786 } 1787} 1788 1789/* Handle the array context */ 1790static void json_parse_array_context (lua_State * l ,json_parse_t * json ) 1791{ 1792json_token_t token ; 1793int i ; 1794 1795/* 2 slots required: 1796* .., table, value */ 1797json_decode_descend (l ,json ,2 ); 1798 1799lua_newtable (l ); 1800 1801/* set array_mt on the table at the top of the stack */ 1802if (json -> cfg -> decode_array_with_array_mt ) { 1803lua_pushlightuserdata (l ,json_lightudata_mask (& json_array )); 1804lua_rawget (l ,LUA_REGISTRYINDEX ); 1805lua_setmetatable (l ,-2 ); 1806 } 1807 1808json_next_token (json ,& token ); 1809 1810/* Handle empty arrays */ 1811if (token .type == T_ARR_END ) { 1812json_decode_ascend (json ); 1813return ; 1814 } 1815 1816for (i = 1 ; ;i ++ ) { 1817json_process_value (l ,json ,& token ,json -> options -> luanil_array ); 1818lua_rawseti (l ,-2 ,i );/* arr[i] = value */ 1819 1820json_next_token (json ,& token ); 1821 1822if (token .type == T_ARR_END ) { 1823json_decode_ascend (json ); 1824return ; 1825 } 1826 1827if (token .type != T_COMMA ) 1828json_throw_parse_error (l ,json ,"comma or array end" ,& token ); 1829 1830json_next_token (json ,& token ); 1831 } 1832} 1833 1834/* Handle the "value" context */ 1835static void json_process_value (lua_State * l ,json_parse_t * json , 1836json_token_t * token ,bool use_luanil ) 1837{ 1838switch (token -> type ) { 1839case T_STRING : 1840lua_pushlstring (l ,token -> value .string ,token -> string_len ); 1841break ;; 1842case T_NUMBER : 1843lua_pushnumber (l ,token -> value .number ); 1844break ;; 1845case T_INTEGER : 1846lua_pushinteger (l ,token -> value .integer ); 1847break ;; 1848case T_BOOLEAN : 1849lua_pushboolean (l ,token -> value .boolean ); 1850break ;; 1851case T_OBJ_BEGIN : 1852json_parse_object_context (l ,json ); 1853break ;; 1854case T_ARR_BEGIN : 1855json_parse_array_context (l ,json ); 1856break ;; 1857case T_NULL : 1858if (use_luanil ) { 1859lua_pushnil (l ); 1860 }else { 1861nlua_pushref (l ,nlua_get_nil_ref (l )); 1862 } 1863break ;; 1864default : 1865json_throw_parse_error (l ,json ,"value" ,token ); 1866 } 1867} 1868 1869static int json_decode (lua_State * l ) 1870{ 1871json_parse_t json ; 1872json_token_t token ; 1873json_options_t options = { .luanil_object = false, .luanil_array = false, .skip_comments = false }; 1874 1875size_t json_len ; 1876 1877switch (lua_gettop (l )) { 1878case 1 : 1879break ; 1880case 2 : 1881luaL_checktype (l ,2 ,LUA_TTABLE ); 1882 1883lua_getfield (l ,2 ,"skip_comments" ); 1884options .skip_comments = lua_toboolean (l ,-1 ); 1885lua_pop (l ,1 ); 1886 1887lua_getfield (l ,2 ,"luanil" ); 1888if (lua_isnil (l ,-1 )) { 1889lua_pop (l ,1 ); 1890break ; 1891 } 1892 1893luaL_checktype (l ,-1 ,LUA_TTABLE ); 1894 1895lua_getfield (l ,-1 ,"object" ); 1896options .luanil_object = lua_toboolean (l ,-1 ); 1897lua_pop (l ,1 ); 1898 1899lua_getfield (l ,-1 ,"array" ); 1900options .luanil_array = lua_toboolean (l ,-1 ); 1901/* Also pop the luanil table */ 1902lua_pop (l ,2 ); 1903break ; 1904default : 1905return luaL_error (l ,"expected 1 or 2 arguments" ); 1906 } 1907 1908json .cfg = json_fetch_config (l ); 1909json .data = luaL_checklstring (l ,1 ,& json_len ); 1910json .options = & options ; 1911json .current_depth = 0 ; 1912json .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. */ 1919if (json_len >=2 && (!json .data [0 ]|| !json .data [1 ])) 1920luaL_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 */ 1925json .tmp = strbuf_new (json_len ); 1926 1927json_next_token (& json ,& token ); 1928json_process_value (l ,& json ,& token ,json .options -> luanil_object ); 1929 1930/* Ensure there is no more input left */ 1931json_next_token (& json ,& token ); 1932 1933if (token .type != T_END ) 1934json_throw_parse_error (l ,& json ,"the end" ,& token ); 1935 1936strbuf_free (json .tmp ); 1937 1938return 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*/ 1950static void compat_luaL_setfuncs (lua_State * l ,const luaL_Reg * reg ,int nup ) 1951{ 1952int i ; 1953 1954luaL_checkstack (l ,nup ,"too many upvalues" ); 1955for (;reg -> name != NULL ;reg ++ ) {/* fill the table with given functions */ 1956for (i = 0 ;i < nup ;i ++ )/* copy upvalues to the top */ 1957lua_pushvalue (l ,- nup ); 1958lua_pushcclosure (l ,reg -> func ,nup );/* closure with those upvalues */ 1959lua_setfield (l ,- (nup + 2 ),reg -> name ); 1960 } 1961lua_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" */ 1970static int json_protect_conversion (lua_State * l ) 1971{ 1972int err ; 1973 1974/* Deliberately throw an error for invalid arguments */ 1975luaL_argcheck (l ,lua_gettop (l )== 1 ,1 ,"expected 1 argument" ); 1976 1977/* pcall() the function stored as upvalue(1) */ 1978lua_pushvalue (l ,lua_upvalueindex (1 )); 1979lua_insert (l ,1 ); 1980err = lua_pcall (l ,1 ,1 ,0 ); 1981if (!err ) 1982return 1 ; 1983 1984if (err == LUA_ERRRUN ) { 1985lua_pushnil (l ); 1986lua_insert (l ,-2 ); 1987return 2 ; 1988 } 1989 1990/* Since we are not using a custom error handler, the only remaining 1991* errors are memory related */ 1992return luaL_error (l ,"Memory allocation error in CJSON protected call" ); 1993} 1994 1995/* Return cjson module table */ 1996int lua_cjson_new (lua_State * l ) 1997{ 1998luaL_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 */ 2023lua_getfield (l ,LUA_REGISTRYINDEX ,"nvim.thread" ); 2024bool is_thread = lua_toboolean (l ,-1 ); 2025lua_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. 2029if (!is_thread ) { 2030fpconv_init (); 2031 } 2032 2033/* Test if array metatables are in registry */ 2034lua_pushlightuserdata (l ,json_lightudata_mask (& json_empty_array )); 2035lua_rawget (l ,LUA_REGISTRYINDEX ); 2036if (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*/ 2043lua_pop (l ,1 ); 2044 2045/* empty_array_mt */ 2046lua_pushlightuserdata (l ,json_lightudata_mask (& json_empty_array )); 2047lua_newtable (l ); 2048lua_rawset (l ,LUA_REGISTRYINDEX ); 2049 2050/* array_mt */ 2051lua_pushlightuserdata (l ,json_lightudata_mask (& json_array )); 2052lua_newtable (l ); 2053lua_rawset (l ,LUA_REGISTRYINDEX ); 2054 } 2055 2056/* cjson module table */ 2057lua_newtable (l ); 2058 2059/* Register functions with config data as upvalue */ 2060json_create_config (l ); 2061compat_luaL_setfuncs (l ,reg ,1 ); 2062 2063// Nvim: don't expose "null", it is identical to vim.NIL. 2064/* 2065nlua_pushref(l, nlua_get_nil_ref(l)); 2066lua_setfield(l, -2, "null"); 2067*/ 2068 2069// Nvim: don't expose empty_array_mt. 2070/* 2071lua_pushlightuserdata(l, json_lightudata_mask(&json_empty_array)); 2072lua_rawget(l, LUA_REGISTRYINDEX); 2073lua_setfield(l, -2, "empty_array_mt"); 2074*/ 2075 2076// Nvim: don't expose array_mt. 2077/* 2078lua_pushlightuserdata(l, json_lightudata_mask(&json_array)); 2079lua_rawget(l, LUA_REGISTRYINDEX); 2080lua_setfield(l, -2, "array_mt"); 2081*/ 2082 2083// Nvim: don't expose empty_array. 2084/* 2085lua_pushlightuserdata(l, json_lightudata_mask(&json_array)); 2086lua_setfield(l, -2, "empty_array"); 2087*/ 2088 2089/* Set module name / version fields */ 2090lua_pushliteral (l ,CJSON_MODNAME ); 2091lua_setfield (l ,-2 ,"_NAME" ); 2092lua_pushliteral (l ,CJSON_VERSION ); 2093lua_setfield (l ,-2 ,"_VERSION" ); 2094 2095return 1 ; 2096} 2097 2098/* Return cjson.safe module table */ 2099static int lua_cjson_safe_new (lua_State * l ) 2100{ 2101const char * func []= {"decode" ,"encode" ,NULL }; 2102int i ; 2103 2104lua_cjson_new (l ); 2105 2106/* Fix new() method */ 2107lua_pushcfunction (l ,lua_cjson_safe_new ); 2108lua_setfield (l ,-2 ,"new" ); 2109 2110for (i = 0 ;func [i ];i ++ ) { 2111lua_getfield (l ,-1 ,func [i ]); 2112lua_pushcclosure (l ,json_protect_conversion ,1 ); 2113lua_setfield (l ,-2 ,func [i ]); 2114 } 2115 2116return 1 ; 2117} 2118 2119int luaopen_cjson (lua_State * l ) 2120{ 2121lua_cjson_new (l ); 2122 2123#ifdef ENABLE_CJSON_GLOBAL 2124/* Register a global "cjson" table. */ 2125lua_pushvalue (l ,-1 ); 2126lua_setglobal (l ,CJSON_MODNAME ); 2127#endif 2128 2129/* Return cjson table */ 2130return 1 ; 2131} 2132 2133int luaopen_cjson_safe (lua_State * l ) 2134{ 2135lua_cjson_safe_new (l ); 2136 2137/* Return cjson.safe table */ 2138return 1 ; 2139} 2140