robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <lauxlib.h> 3#include <lua.h> 4#include <stdbool.h> 5#include <stddef.h> 6#include <stdint.h> 7#include <stdlib.h> 8#include <string.h> 9 10#include "klib/kvec.h" 11#include "nvim/api/private/defs.h" 12#include "nvim/api/private/helpers.h" 13#include "nvim/ascii_defs.h" 14#include "nvim/eval/decode.h" 15#include "nvim/eval/typval.h" 16#include "nvim/eval/typval_defs.h" 17#include "nvim/eval/typval_encode.h" 18#include "nvim/eval/userfunc.h" 19#include "nvim/gettext_defs.h" 20#include "nvim/highlight_group.h" 21#include "nvim/lua/converter.h" 22#include "nvim/lua/executor.h" 23#include "nvim/macros_defs.h" 24#include "nvim/memory.h" 25#include "nvim/memory_defs.h" 26#include "nvim/message.h" 27#include "nvim/types_defs.h" 28#include "nvim/vim_defs.h" 29 30/// Determine, which keys Lua table contains 31typedef struct { 32size_t maxidx ;///< Maximum positive integral value found. 33size_t string_keys_num ;///< Number of string keys. 34bool has_string_with_nul ;///< True if there is string key with NUL byte. 35ObjectType type ;///< If has_type_key is true then attached value. Otherwise 36///< either kObjectTypeNil, kObjectTypeDict or 37///< kObjectTypeArray, depending on other properties. 38lua_Number val ;///< If has_val_key and val_type == LUA_TNUMBER: value. 39bool has_type_key ;///< True if type key is present. 40}LuaTableProps ; 41 42#include "lua/converter.c.generated.h" 43 44#define TYPE_IDX_VALUE true 45#define VAL_IDX_VALUE false 46 47#define LUA_PUSH_STATIC_STRING (lstate ,s ) \ 48 lua_pushlstring(lstate, s, sizeof(s) - 1) 49 50static LuaTableProps nlua_traverse_table (lua_State * const lstate ) 51FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 52{ 53size_t tsize = 0 ;// Total number of keys. 54int val_type = 0 ;// If has_val_key: Lua type of the value. 55bool has_val_key = false;// True if val key was found, 56// @see nlua_push_val_idx(). 57size_t other_keys_num = 0 ;// Number of keys that are not string, integral 58// or type keys. 59LuaTableProps ret ; 60CLEAR_FIELD (ret ); 61if (!lua_checkstack (lstate ,lua_gettop (lstate )+ 3 )) { 62semsg (_ ("E1502: Lua failed to grow stack to %i" ),lua_gettop (lstate )+ 2 ); 63ret .type = kObjectTypeNil ; 64return ret ; 65 } 66lua_pushnil (lstate ); 67while (lua_next (lstate ,-2 )) { 68switch (lua_type (lstate ,-2 )) { 69case LUA_TSTRING : { 70size_t len ; 71const char * s = lua_tolstring (lstate ,-2 ,& len ); 72if (memchr (s ,NUL ,len )!= NULL ) { 73ret .has_string_with_nul = true; 74 } 75ret .string_keys_num ++ ; 76break ; 77 } 78case LUA_TNUMBER : { 79const lua_Number n = lua_tonumber (lstate ,-2 ); 80if (n > (lua_Number )SIZE_MAX || n <=0 81|| ((lua_Number )((size_t )n ))!= n ) { 82other_keys_num ++ ; 83 }else { 84const size_t idx = (size_t )n ; 85if (idx > ret .maxidx ) { 86ret .maxidx = idx ; 87 } 88 } 89break ; 90 } 91case LUA_TBOOLEAN : { 92const bool b = lua_toboolean (lstate ,-2 ); 93if (b == TYPE_IDX_VALUE ) { 94if (lua_type (lstate ,-1 )== LUA_TNUMBER ) { 95lua_Number n = lua_tonumber (lstate ,-1 ); 96if (n == (lua_Number )kObjectTypeFloat 97|| n == (lua_Number )kObjectTypeArray 98|| n == (lua_Number )kObjectTypeDict ) { 99ret .has_type_key = true; 100ret .type = (ObjectType )n ; 101 }else { 102other_keys_num ++ ; 103 } 104 }else { 105other_keys_num ++ ; 106 } 107 }else { 108has_val_key = true; 109val_type = lua_type (lstate ,-1 ); 110if (val_type == LUA_TNUMBER ) { 111ret .val = lua_tonumber (lstate ,-1 ); 112 } 113 } 114break ; 115 } 116default : 117other_keys_num ++ ; 118break ; 119 } 120tsize ++ ; 121lua_pop (lstate ,1 ); 122 } 123if (ret .has_type_key ) { 124assert (tsize > 0 ); 125if (ret .type == kObjectTypeFloat 126&& (!has_val_key || val_type != LUA_TNUMBER )) { 127ret .type = kObjectTypeNil ; 128 }else if (ret .type == kObjectTypeArray ) { 129// Determine what is the last number in a *sequence* of keys. 130// This condition makes sure that Neovim will not crash when it gets table 131// {[vim.type_idx]=vim.types.array, [SIZE_MAX]=1}: without it maxidx will 132// be SIZE_MAX, with this condition it should be zero and [SIZE_MAX] key 133// should be ignored. 134if (ret .maxidx != 0 135&& ret .maxidx != (tsize 136- ret .has_type_key 137- other_keys_num 138- has_val_key 139- ret .string_keys_num )) { 140for (ret .maxidx = 0 ;;ret .maxidx ++ ) { 141lua_rawgeti (lstate ,-1 , (int )ret .maxidx + 1 ); 142if (lua_isnil (lstate ,-1 )) { 143lua_pop (lstate ,1 ); 144break ; 145 } 146lua_pop (lstate ,1 ); 147 } 148 } 149 } 150 }else { 151if (tsize == 0 152|| (tsize <=ret .maxidx 153&& other_keys_num == 0 154&& ret .string_keys_num == 0 )) { 155ret .type = kObjectTypeArray ; 156if (tsize == 0 && lua_getmetatable (lstate ,-1 )) { 157nlua_pushref (lstate ,nlua_global_refs -> empty_dict_ref ); 158if (lua_rawequal (lstate ,-2 ,-1 )) { 159ret .type = kObjectTypeDict ; 160 } 161lua_pop (lstate ,2 ); 162 } 163 }else if (ret .string_keys_num == tsize ) { 164ret .type = kObjectTypeDict ; 165 }else { 166ret .type = kObjectTypeNil ; 167 } 168 } 169return ret ; 170} 171 172/// Helper structure for nlua_pop_typval 173typedef struct { 174typval_T * tv ;///< Location where conversion result is saved. 175size_t list_len ;///< Maximum length when tv is a list. 176bool container ;///< True if tv is a container. 177bool special ;///< If true then tv is a _VAL part of special dict. 178///< that represents mapping. 179int idx ;///< Container index (used to detect self-referencing structures). 180}TVPopStackItem ; 181 182/// Convert Lua object to Vimscript typval_T 183/// 184/// Should pop exactly one value from Lua stack. 185/// 186/// @param lstate Lua state. 187/// @param[out] ret_tv Where to put the result. 188/// 189/// @return `true` in case of success, `false` in case of failure. Error is 190/// reported automatically. 191bool nlua_pop_typval (lua_State * lstate ,typval_T * ret_tv ) 192{ 193bool ret = true; 194const int initial_size = lua_gettop (lstate ); 195kvec_withinit_t (TVPopStackItem ,2 )stack = KV_INITIAL_VALUE ; 196kvi_init (stack ); 197kvi_push (stack , ((TVPopStackItem ){ .tv = ret_tv })); 198while (ret && kv_size (stack )) { 199if (!lua_checkstack (lstate ,lua_gettop (lstate )+ 3 )) { 200semsg (_ ("E1502: Lua failed to grow stack to %i" ),lua_gettop (lstate )+ 3 ); 201ret = false; 202break ; 203 } 204TVPopStackItem cur = kv_pop (stack ); 205if (cur .container ) { 206if (cur .special || cur .tv -> v_type == VAR_DICT ) { 207assert (cur .tv -> v_type == (cur .special ?VAR_LIST :VAR_DICT )); 208bool next_key_found = false; 209while (lua_next (lstate ,-2 )) { 210if (lua_type (lstate ,-2 )== LUA_TSTRING ) { 211next_key_found = true; 212break ; 213 } 214lua_pop (lstate ,1 ); 215 } 216if (next_key_found ) { 217size_t len ; 218const char * s = lua_tolstring (lstate ,-2 ,& len ); 219if (cur .special ) { 220list_T * const kv_pair = tv_list_alloc (2 ); 221 222typval_T s_tv = decode_string (s ,len , true, false); 223tv_list_append_owned_tv (kv_pair ,s_tv ); 224 225// Value: not populated yet, need to create list item to push. 226tv_list_append_owned_tv (kv_pair , (typval_T ) { 227 .v_type = VAR_UNKNOWN , 228 }); 229kvi_push (stack ,cur ); 230tv_list_append_list (cur .tv -> vval .v_list ,kv_pair ); 231cur = (TVPopStackItem ){ .tv = TV_LIST_ITEM_TV (tv_list_last (kv_pair )) }; 232 }else { 233dictitem_T * const di = tv_dict_item_alloc_len (s ,len ); 234if (tv_dict_add (cur .tv -> vval .v_dict ,di )== FAIL ) { 235abort (); 236 } 237kvi_push (stack ,cur ); 238cur = (TVPopStackItem ){ .tv = & di -> di_tv }; 239 } 240 }else { 241lua_pop (lstate ,1 ); 242continue ; 243 } 244 }else { 245assert (cur .tv -> v_type == VAR_LIST ); 246if ((size_t )tv_list_len (cur .tv -> vval .v_list )== cur .list_len ) { 247lua_pop (lstate ,1 ); 248continue ; 249 } 250lua_rawgeti (lstate ,-1 ,tv_list_len (cur .tv -> vval .v_list )+ 1 ); 251// Not populated yet, need to create list item to push. 252tv_list_append_owned_tv (cur .tv -> vval .v_list , (typval_T ) { 253 .v_type = VAR_UNKNOWN , 254 }); 255kvi_push (stack ,cur ); 256// TODO(ZyX-I): Use indexes, here list item *will* be reallocated. 257cur = (TVPopStackItem ){ .tv = TV_LIST_ITEM_TV (tv_list_last (cur .tv -> vval .v_list )) }; 258 } 259 } 260assert (!cur .container ); 261* cur .tv = (typval_T ) { 262 .v_type = VAR_NUMBER , 263 .v_lock = VAR_UNLOCKED , 264 .vval = { .v_number = 0 }, 265 }; 266switch (lua_type (lstate ,-1 )) { 267case LUA_TNIL : 268cur .tv -> v_type = VAR_SPECIAL ; 269cur .tv -> vval .v_special = kSpecialVarNull ; 270break ; 271case LUA_TBOOLEAN : 272cur .tv -> v_type = VAR_BOOL ; 273cur .tv -> vval .v_bool = (lua_toboolean (lstate ,-1 ) ?kBoolVarTrue :kBoolVarFalse ); 274break ; 275case LUA_TSTRING : { 276size_t len ; 277const char * s = lua_tolstring (lstate ,-1 ,& len ); 278* cur .tv = decode_string (s ,len , false, false); 279break ; 280 } 281case LUA_TNUMBER : { 282const lua_Number n = lua_tonumber (lstate ,-1 ); 283if (n > (lua_Number )VARNUMBER_MAX || n < (lua_Number )VARNUMBER_MIN 284|| ((lua_Number )((varnumber_T )n ))!= n ) { 285cur .tv -> v_type = VAR_FLOAT ; 286cur .tv -> vval .v_float = (float_T )n ; 287 }else { 288cur .tv -> v_type = VAR_NUMBER ; 289cur .tv -> vval .v_number = (varnumber_T )n ; 290 } 291break ; 292 } 293case LUA_TTABLE : { 294// Only need to track table refs if we have a metatable associated. 295LuaRef table_ref = LUA_NOREF ; 296if (lua_getmetatable (lstate ,-1 )) { 297lua_pop (lstate ,1 ); 298table_ref = nlua_ref_global (lstate ,-1 ); 299 } 300 301const LuaTableProps table_props = nlua_traverse_table (lstate ); 302 303for (size_t i = 0 ;i < kv_size (stack );i ++ ) { 304const TVPopStackItem item = kv_A (stack ,i ); 305if (item .container && lua_rawequal (lstate ,-1 ,item .idx )) { 306tv_copy (item .tv ,cur .tv ); 307cur .container = false; 308 gotonlua_pop_typval_table_processing_end ; 309 } 310 } 311 312switch (table_props .type ) { 313case kObjectTypeArray : 314cur .tv -> v_type = VAR_LIST ; 315cur .tv -> vval .v_list = tv_list_alloc ((ptrdiff_t )table_props .maxidx ); 316cur .tv -> vval .v_list -> lua_table_ref = table_ref ; 317tv_list_ref (cur .tv -> vval .v_list ); 318cur .list_len = table_props .maxidx ; 319if (table_props .maxidx != 0 ) { 320cur .container = true; 321cur .idx = lua_gettop (lstate ); 322kvi_push (stack ,cur ); 323 } 324break ; 325case kObjectTypeDict : 326if (table_props .string_keys_num == 0 ) { 327cur .tv -> v_type = VAR_DICT ; 328cur .tv -> vval .v_dict = tv_dict_alloc (); 329cur .tv -> vval .v_dict -> dv_refcount ++ ; 330cur .tv -> vval .v_dict -> lua_table_ref = table_ref ; 331 }else { 332cur .special = table_props .has_string_with_nul ; 333if (table_props .has_string_with_nul ) { 334decode_create_map_special_dict (cur .tv , (ptrdiff_t )table_props .string_keys_num ); 335assert (cur .tv -> v_type == VAR_DICT ); 336dictitem_T * const val_di = tv_dict_find (cur .tv -> vval .v_dict , 337S_LEN ("_VAL" )); 338assert (val_di != NULL ); 339cur .tv = & val_di -> di_tv ; 340cur .tv -> vval .v_list -> lua_table_ref = table_ref ; 341assert (cur .tv -> v_type == VAR_LIST ); 342cur .list_len = table_props .string_keys_num ; 343 }else { 344cur .tv -> v_type = VAR_DICT ; 345cur .tv -> vval .v_dict = tv_dict_alloc (); 346cur .tv -> vval .v_dict -> dv_refcount ++ ; 347cur .tv -> vval .v_dict -> lua_table_ref = table_ref ; 348 } 349cur .container = true; 350cur .idx = lua_gettop (lstate ); 351kvi_push (stack ,cur ); 352lua_pushnil (lstate ); 353 } 354break ; 355case kObjectTypeFloat : 356cur .tv -> v_type = VAR_FLOAT ; 357cur .tv -> vval .v_float = (float_T )table_props .val ; 358break ; 359case kObjectTypeNil : 360emsg (_ ("E5100: Cannot convert given Lua table: table should " 361"contain either only integer keys or only string keys" )); 362ret = false; 363break ; 364default : 365abort (); 366 } 367nlua_pop_typval_table_processing_end : 368break ; 369 } 370case LUA_TFUNCTION : { 371LuaRef func = nlua_ref_global (lstate ,-1 ); 372 373char * name = register_luafunc (func ); 374 375cur .tv -> v_type = VAR_FUNC ; 376cur .tv -> vval .v_string = xstrdup (name ); 377break ; 378 } 379case LUA_TUSERDATA : { 380// TODO(bfredl): check mt.__call and convert to function? 381nlua_pushref (lstate ,nlua_global_refs -> nil_ref ); 382bool is_nil = lua_rawequal (lstate ,-2 ,-1 ); 383lua_pop (lstate ,1 ); 384if (is_nil ) { 385cur .tv -> v_type = VAR_SPECIAL ; 386cur .tv -> vval .v_special = kSpecialVarNull ; 387 }else { 388emsg (_ ("E5101: Cannot convert given Lua type" )); 389ret = false; 390 } 391break ; 392 } 393default : 394emsg (_ ("E5101: Cannot convert given Lua type" )); 395ret = false; 396break ; 397 } 398if (!cur .container ) { 399lua_pop (lstate ,1 ); 400 } 401 } 402kvi_destroy (stack ); 403if (!ret ) { 404tv_clear (ret_tv ); 405* ret_tv = (typval_T ) { 406 .v_type = VAR_NUMBER , 407 .v_lock = VAR_UNLOCKED , 408 .vval = { .v_number = 0 }, 409 }; 410lua_pop (lstate ,lua_gettop (lstate )- initial_size + 1 ); 411 } 412assert (lua_gettop (lstate )== initial_size - 1 ); 413return ret ; 414} 415 416static bool typval_conv_special = false; 417 418#define TYPVAL_ENCODE_ALLOW_SPECIALS true 419 420#define TYPVAL_ENCODE_CHECK_BEFORE 421 422#define TYPVAL_ENCODE_CONV_NIL (tv ) \ 423 do { \ 424 if (typval_conv_special) { \ 425 lua_pushnil(lstate); \ 426 } else { \ 427 nlua_pushref(lstate, nlua_global_refs->nil_ref); \ 428 } \ 429 } while (0) 430 431#define TYPVAL_ENCODE_CONV_BOOL (tv ,num ) \ 432 lua_pushboolean(lstate, (bool)(num)) 433 434#define TYPVAL_ENCODE_CONV_NUMBER (tv ,num ) \ 435 lua_pushnumber(lstate, (lua_Number)(num)) 436 437#define TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER TYPVAL_ENCODE_CONV_NUMBER 438 439#define TYPVAL_ENCODE_CONV_FLOAT (tv ,flt ) \ 440 TYPVAL_ENCODE_CONV_NUMBER(tv, flt) 441 442#define TYPVAL_ENCODE_CONV_STRING (tv ,str ,len ) \ 443 lua_pushlstring(lstate, (str), (len)) 444 445#define TYPVAL_ENCODE_CONV_STR_STRING TYPVAL_ENCODE_CONV_STRING 446 447#define TYPVAL_ENCODE_CONV_EXT_STRING (tv ,str ,len ,type ) \ 448 TYPVAL_ENCODE_CONV_NIL(tv) 449 450#define TYPVAL_ENCODE_CONV_BLOB (tv ,blob ,len ) \ 451 do { \ 452 const blob_T *const blob_ = (blob); \ 453 lua_pushlstring(lstate, blob_ != NULL ? blob_->bv_ga.ga_data : "", (size_t)(len)); \ 454 } while (0) 455 456#define TYPVAL_ENCODE_CONV_FUNC_START (tv ,fun ,prefix ) \ 457 do { \ 458 const char *const fun_ = (fun); \ 459 ufunc_T *fp; \ 460 if (fun_ != NULL && (fp = find_func(fun_)) != NULL && fp->uf_flags & FC_LUAREF) { \ 461 nlua_pushref(lstate, fp->uf_luaref); \ 462 } else { \ 463 TYPVAL_ENCODE_CONV_NIL(tv); \ 464 } \ 465 goto typval_encode_stop_converting_one_item; \ 466 } while (0) 467 468#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS (tv ,len ) 469#define TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF (tv ,len ) 470#define TYPVAL_ENCODE_CONV_FUNC_END (tv ) 471 472#define TYPVAL_ENCODE_CONV_EMPTY_LIST (tv ) \ 473 lua_createtable(lstate, 0, 0) 474 475#define TYPVAL_ENCODE_CONV_EMPTY_DICT (tv ,dict ) \ 476 do { \ 477 if (typval_conv_special) { \ 478 nlua_create_typed_table(lstate, 0, 0, kObjectTypeDict); \ 479 } else { \ 480 lua_createtable(lstate, 0, 0); \ 481 nlua_pushref(lstate, nlua_global_refs->empty_dict_ref); \ 482 lua_setmetatable(lstate, -2); \ 483 } \ 484 } while (0) 485 486#define TYPVAL_ENCODE_CONV_LIST_START (tv ,len ) \ 487 do { \ 488 if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { \ 489 semsg(_("E5102: Lua failed to grow stack to %i"), \ 490 lua_gettop(lstate) + 3); \ 491 return false; \ 492 } \ 493 lua_createtable(lstate, (int)(len), 0); \ 494 lua_pushnumber(lstate, 1); \ 495 } while (0) 496 497#define TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START (tv ,mpsv ) 498 499#define TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS (tv ) \ 500 do { \ 501 lua_Number idx = lua_tonumber(lstate, -2); \ 502 lua_rawset(lstate, -3); \ 503 lua_pushnumber(lstate, idx + 1); \ 504 } while (0) 505 506#define TYPVAL_ENCODE_CONV_LIST_END (tv ) \ 507 lua_rawset(lstate, -3) 508 509#define TYPVAL_ENCODE_CONV_DICT_START (tv ,dict ,len ) \ 510 do { \ 511 if (!lua_checkstack(lstate, lua_gettop(lstate) + 3)) { \ 512 semsg(_("E5102: Lua failed to grow stack to %i"), \ 513 lua_gettop(lstate) + 3); \ 514 return false; \ 515 } \ 516 lua_createtable(lstate, 0, (int)(len)); \ 517 } while (0) 518 519#define TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK (label ,kv_pair ) 520 521#define TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START (tv ,dict ,mpsv ) 522 523#define TYPVAL_ENCODE_CONV_DICT_AFTER_KEY (tv ,dict ) 524 525#define TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS (tv ,dict ) \ 526 lua_rawset(lstate, -3) 527 528#define TYPVAL_ENCODE_CONV_DICT_END (tv ,dict ) \ 529 TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS(tv, dict) 530 531#define TYPVAL_ENCODE_CONV_RECURSE (val ,conv_type ) \ 532 do { \ 533 for (size_t backref = kv_size(*mpstack); backref; backref--) { \ 534 const MPConvStackVal mpval = kv_A(*mpstack, backref - 1); \ 535 if (mpval.type == conv_type) { \ 536 if (conv_type == kMPConvDict \ 537 ? (void *)mpval.data.d.dict == (void *)(val) \ 538 : (void *)mpval.data.l.list == (void *)(val)) { \ 539 lua_pushvalue(lstate, \ 540 -((int)((kv_size(*mpstack) - backref + 1) * 2))); \ 541 break; \ 542 } \ 543 } \ 544 } \ 545 } while (0) 546 547#define TYPVAL_ENCODE_SCOPE static 548#define TYPVAL_ENCODE_NAME lua 549#define TYPVAL_ENCODE_FIRST_ARG_TYPE lua_State *const 550#define TYPVAL_ENCODE_FIRST_ARG_NAME lstate 551#include "nvim/eval/typval_encode.c.h" 552 553#undef TYPVAL_ENCODE_SCOPE 554#undef TYPVAL_ENCODE_NAME 555#undef TYPVAL_ENCODE_FIRST_ARG_TYPE 556#undef TYPVAL_ENCODE_FIRST_ARG_NAME 557 558#undef TYPVAL_ENCODE_CONV_STRING 559#undef TYPVAL_ENCODE_CONV_STR_STRING 560#undef TYPVAL_ENCODE_CONV_EXT_STRING 561#undef TYPVAL_ENCODE_CONV_BLOB 562#undef TYPVAL_ENCODE_CONV_NUMBER 563#undef TYPVAL_ENCODE_CONV_FLOAT 564#undef TYPVAL_ENCODE_CONV_FUNC_START 565#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_ARGS 566#undef TYPVAL_ENCODE_CONV_FUNC_BEFORE_SELF 567#undef TYPVAL_ENCODE_CONV_FUNC_END 568#undef TYPVAL_ENCODE_CONV_EMPTY_LIST 569#undef TYPVAL_ENCODE_CONV_LIST_START 570#undef TYPVAL_ENCODE_CONV_REAL_LIST_AFTER_START 571#undef TYPVAL_ENCODE_CONV_EMPTY_DICT 572#undef TYPVAL_ENCODE_CHECK_BEFORE 573#undef TYPVAL_ENCODE_CONV_NIL 574#undef TYPVAL_ENCODE_CONV_BOOL 575#undef TYPVAL_ENCODE_CONV_UNSIGNED_NUMBER 576#undef TYPVAL_ENCODE_CONV_DICT_START 577#undef TYPVAL_ENCODE_CONV_REAL_DICT_AFTER_START 578#undef TYPVAL_ENCODE_CONV_DICT_END 579#undef TYPVAL_ENCODE_CONV_DICT_AFTER_KEY 580#undef TYPVAL_ENCODE_CONV_DICT_BETWEEN_ITEMS 581#undef TYPVAL_ENCODE_SPECIAL_DICT_KEY_CHECK 582#undef TYPVAL_ENCODE_CONV_LIST_END 583#undef TYPVAL_ENCODE_CONV_LIST_BETWEEN_ITEMS 584#undef TYPVAL_ENCODE_CONV_RECURSE 585#undef TYPVAL_ENCODE_ALLOW_SPECIALS 586 587/// Convert Vimscript typval_T to Lua value 588/// 589/// Should leave single value in Lua stack. May only fail if Lua failed to grow stack. 590/// 591/// @param lstate Lua interpreter state. 592/// @param[in] tv typval_T to convert. 593/// 594/// @return true in case of success, false otherwise. 595bool nlua_push_typval (lua_State * lstate ,typval_T * const tv ,int flags ) 596{ 597typval_conv_special = (flags & kNluaPushSpecial ); 598const int initial_size = lua_gettop (lstate ); 599 600if (!lua_checkstack (lstate ,initial_size + 2 )) { 601semsg (_ ("E1502: Lua failed to grow stack to %i" ),initial_size + 4 ); 602return false; 603 } 604if (encode_vim_to_lua (lstate ,tv ,"nlua_push_typval argument" )== FAIL ) { 605return false; 606 } 607assert (lua_gettop (lstate )== initial_size + 1 ); 608return true; 609} 610 611/// Push value which is a type index 612/// 613/// Used for all “typed” tables: i.e. for all tables which represent Vimscript values. 614static inline void nlua_push_type_idx (lua_State * lstate ) 615FUNC_ATTR_NONNULL_ALL 616{ 617lua_pushboolean (lstate ,TYPE_IDX_VALUE ); 618} 619 620/// Push value which is a value index 621/// 622/// Used for tables which represent scalar values, like float value. 623static inline void nlua_push_val_idx (lua_State * lstate ) 624FUNC_ATTR_NONNULL_ALL 625{ 626lua_pushboolean (lstate ,VAL_IDX_VALUE ); 627} 628 629/// Push type 630/// 631/// Type is a value in vim.types table. 632/// 633/// @param[out] lstate Lua state. 634/// @param[in] type Type to push. 635static inline void nlua_push_type (lua_State * lstate ,ObjectType type ) 636FUNC_ATTR_NONNULL_ALL 637{ 638lua_pushnumber (lstate , (lua_Number )type ); 639} 640 641/// Create Lua table which has an entry that determines its Vimscript type 642/// 643/// @param[out] lstate Lua state. 644/// @param[in] narr Number of “array” entries to be populated later. 645/// @param[in] nrec Number of “dictionary” entries to be populated later. 646/// @param[in] type Type of the table. 647static inline void nlua_create_typed_table (lua_State * lstate ,const size_t narr ,const size_t nrec , 648const ObjectType type ) 649FUNC_ATTR_NONNULL_ALL 650{ 651lua_createtable (lstate , (int )narr , (int )(1 + nrec )); 652nlua_push_type_idx (lstate ); 653nlua_push_type (lstate ,type ); 654lua_rawset (lstate ,-3 ); 655} 656 657/// Convert given String to Lua string 658/// 659/// Leaves converted string on top of the stack. 660void nlua_push_String (lua_State * lstate ,const String s ,int flags ) 661FUNC_ATTR_NONNULL_ALL 662{ 663lua_pushlstring (lstate ,s .size ?s .data :"" ,s .size ); 664} 665 666/// Convert given Integer to Lua number 667/// 668/// Leaves converted number on top of the stack. 669void nlua_push_Integer (lua_State * lstate ,const Integer n ,int flags ) 670FUNC_ATTR_NONNULL_ALL 671{ 672lua_pushnumber (lstate , (lua_Number )n ); 673} 674 675/// Convert given Float to Lua table 676/// 677/// Leaves converted table on top of the stack. 678void nlua_push_Float (lua_State * lstate ,const Float f ,int flags ) 679FUNC_ATTR_NONNULL_ALL 680{ 681if (flags & kNluaPushSpecial ) { 682nlua_create_typed_table (lstate ,0 ,1 ,kObjectTypeFloat ); 683nlua_push_val_idx (lstate ); 684lua_pushnumber (lstate , (lua_Number )f ); 685lua_rawset (lstate ,-3 ); 686 }else { 687lua_pushnumber (lstate , (lua_Number )f ); 688 } 689} 690 691/// Convert given Float to Lua boolean 692/// 693/// Leaves converted value on top of the stack. 694void nlua_push_Boolean (lua_State * lstate ,const Boolean b ,int flags ) 695FUNC_ATTR_NONNULL_ALL 696{ 697lua_pushboolean (lstate ,b ); 698} 699 700/// Convert given Dict to Lua table 701/// 702/// Leaves converted table on top of the stack. 703void nlua_push_Dict (lua_State * lstate ,const Dict dict ,int flags ) 704FUNC_ATTR_NONNULL_ALL 705{ 706lua_createtable (lstate ,0 , (int )dict .size ); 707if (dict .size == 0 ) { 708nlua_pushref (lstate ,nlua_global_refs -> empty_dict_ref ); 709lua_setmetatable (lstate ,-2 ); 710 } 711for (size_t i = 0 ;i < dict .size ;i ++ ) { 712nlua_push_String (lstate ,dict .items [i ].key ,flags ); 713nlua_push_Object (lstate ,& dict .items [i ].value ,flags ); 714lua_rawset (lstate ,-3 ); 715 } 716} 717 718/// Convert given Array to Lua table 719/// 720/// Leaves converted table on top of the stack. 721void nlua_push_Array (lua_State * lstate ,const Array array ,int flags ) 722FUNC_ATTR_NONNULL_ALL 723{ 724lua_createtable (lstate , (int )array .size ,0 ); 725for (size_t i = 0 ;i < array .size ;i ++ ) { 726nlua_push_Object (lstate ,& array .items [i ],flags ); 727lua_rawseti (lstate ,-2 , (int )i + 1 ); 728 } 729} 730 731void nlua_push_handle (lua_State * lstate ,const handle_T item ,int flags ) 732FUNC_ATTR_NONNULL_ALL 733{ 734lua_pushnumber (lstate , (lua_Number )item ); 735} 736 737/// Convert given Object to Lua value 738/// 739/// Leaves converted value on top of the stack. 740void nlua_push_Object (lua_State * lstate ,Object * obj ,int flags ) 741FUNC_ATTR_NONNULL_ALL 742{ 743switch (obj -> type ) { 744case kObjectTypeUnset : 745case kObjectTypeNil : 746if (flags & kNluaPushSpecial ) { 747lua_pushnil (lstate ); 748 }else { 749nlua_pushref (lstate ,nlua_global_refs -> nil_ref ); 750 } 751break ; 752case kObjectTypeLuaRef : { 753nlua_pushref (lstate ,obj -> data .luaref ); 754if (flags & kNluaPushFreeRefs ) { 755api_free_luaref (obj -> data .luaref ); 756obj -> data .luaref = LUA_NOREF ; 757 } 758break ; 759 } 760#define ADD_TYPE (type ,data_key ) \ 761 case kObjectType##type: { \ 762 nlua_push_##type(lstate, obj->data.data_key, flags); \ 763 break; \ 764 } 765ADD_TYPE (Boolean ,boolean ) 766ADD_TYPE (Integer ,integer ) 767ADD_TYPE (Float ,floating ) 768ADD_TYPE (String ,string ) 769ADD_TYPE (Array ,array ) 770ADD_TYPE (Dict ,dict ) 771#undef ADD_TYPE 772#define ADD_REMOTE_TYPE (type ) \ 773 case kObjectType##type: { \ 774 nlua_push_##type(lstate, (type)obj->data.integer, flags); \ 775 break; \ 776 } 777ADD_REMOTE_TYPE (Buffer ) 778ADD_REMOTE_TYPE (Window ) 779ADD_REMOTE_TYPE (Tabpage ) 780#undef ADD_REMOTE_TYPE 781 } 782} 783 784/// Convert Lua value to string 785/// 786/// Always pops one value from the stack. 787String nlua_pop_String (lua_State * lstate ,Arena * arena ,Error * err ) 788FUNC_ATTR_NONNULL_ARG (1 ,3 )FUNC_ATTR_WARN_UNUSED_RESULT 789{ 790if (lua_type (lstate ,-1 )!= LUA_TSTRING ) { 791lua_pop (lstate ,1 ); 792api_set_error (err ,kErrorTypeValidation ,"Expected Lua string" ); 793return (String ) { .size = 0 , .data = NULL }; 794 } 795String ret ; 796 797ret .data = (char * )lua_tolstring (lstate ,-1 ,& (ret .size )); 798assert (ret .data != NULL ); 799// TODO(bfredl): it would be "nice" to just use the memory of the Lua string 800// directly, although ensuring the lifetime of such strings is a bit tricky 801// (an API call could invoke nested Lua, which triggers GC, and kaboom?) 802ret .data = arena_memdupz (arena ,ret .data ,ret .size ); 803lua_pop (lstate ,1 ); 804 805return ret ; 806} 807 808/// Convert Lua value to integer 809/// 810/// Always pops one value from the stack. 811Integer nlua_pop_Integer (lua_State * lstate ,Arena * arena ,Error * err ) 812FUNC_ATTR_NONNULL_ARG (1 ,3 )FUNC_ATTR_WARN_UNUSED_RESULT 813{ 814if (lua_type (lstate ,-1 )!= LUA_TNUMBER ) { 815lua_pop (lstate ,1 ); 816api_set_error (err ,kErrorTypeValidation ,"Expected Lua number" ); 817return 0 ; 818 } 819const lua_Number n = lua_tonumber (lstate ,-1 ); 820lua_pop (lstate ,1 ); 821if (n > (lua_Number )API_INTEGER_MAX || n < (lua_Number )API_INTEGER_MIN 822|| ((lua_Number )((Integer )n ))!= n ) { 823api_set_error (err ,kErrorTypeException ,"Number is not integral" ); 824return 0 ; 825 } 826return (Integer )n ; 827} 828 829/// Convert Lua value to boolean 830/// 831/// Despite the name of the function, this uses Lua semantics for booleans. 832/// thus `err` is never set as any Lua value can be co-erced into a Lua bool 833/// 834/// Always pops one value from the stack. 835Boolean nlua_pop_Boolean (lua_State * lstate ,Arena * arena ,Error * err ) 836FUNC_ATTR_NONNULL_ARG (1 ,3 )FUNC_ATTR_WARN_UNUSED_RESULT 837{ 838const Boolean ret = lua_toboolean (lstate ,-1 ); 839lua_pop (lstate ,1 ); 840return ret ; 841} 842 843/// Convert Lua value to boolean 844/// 845/// This follows API conventions for a Boolean value, compare api_object_to_bool 846/// 847/// Always pops one value from the stack. 848Boolean nlua_pop_Boolean_strict (lua_State * lstate ,Error * err ) 849FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 850{ 851Boolean ret = false; 852switch (lua_type (lstate ,-1 )) { 853case LUA_TBOOLEAN : 854ret = lua_toboolean (lstate ,-1 ); 855break ; 856 857case LUA_TNUMBER : 858ret = (lua_tonumber (lstate ,-1 )!= 0 ); 859break ; 860 861case LUA_TNIL : 862ret = false; 863break ; 864 865default : 866api_set_error (err ,kErrorTypeValidation ,"not a boolean" ); 867 } 868 869lua_pop (lstate ,1 ); 870return ret ; 871} 872 873/// Check whether typed table on top of the stack has given type 874/// 875/// @param[in] lstate Lua state. 876/// @param[out] err Location where error will be saved. May be NULL. 877/// @param[in] type Type to check. 878/// 879/// @return @see nlua_traverse_table(). 880static inline LuaTableProps nlua_check_type (lua_State * const lstate ,Error * const err , 881const ObjectType type ) 882FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_WARN_UNUSED_RESULT 883{ 884if (lua_type (lstate ,-1 )!= LUA_TTABLE ) { 885if (err ) { 886api_set_error (err ,kErrorTypeValidation ,"Expected Lua %s" , 887 (type == kObjectTypeFloat ) ?"number" :"table" ); 888 } 889return (LuaTableProps ) { .type = kObjectTypeNil }; 890 } 891LuaTableProps table_props = nlua_traverse_table (lstate ); 892 893if (type == kObjectTypeDict && table_props .type == kObjectTypeArray 894&& table_props .maxidx == 0 && !table_props .has_type_key ) { 895table_props .type = kObjectTypeDict ; 896 } 897 898if (table_props .type != type ) { 899if (err ) { 900api_set_error (err ,kErrorTypeValidation ,"Expected %s-like Lua table" ,api_typename (type )); 901 } 902 } 903 904return table_props ; 905} 906 907/// Convert Lua table to float 908/// 909/// Always pops one value from the stack. 910Float nlua_pop_Float (lua_State * lstate ,Arena * arena ,Error * err ) 911FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 912{ 913if (lua_type (lstate ,-1 )== LUA_TNUMBER ) { 914const Float ret = (Float )lua_tonumber (lstate ,-1 ); 915lua_pop (lstate ,1 ); 916return ret ; 917 } 918 919const LuaTableProps table_props = nlua_check_type (lstate ,err , 920kObjectTypeFloat ); 921lua_pop (lstate ,1 ); 922if (table_props .type != kObjectTypeFloat ) { 923return 0 ; 924 } 925return (Float )table_props .val ; 926} 927 928/// Convert Lua table to array without determining whether it is array 929/// 930/// @param lstate Lua state. 931/// @param[in] table_props nlua_traverse_table() output. 932/// @param[out] err Location where error will be saved. 933static Array nlua_pop_Array_unchecked (lua_State * const lstate ,const LuaTableProps table_props , 934Arena * arena ,Error * const err ) 935{ 936Array ret = arena_array (arena ,table_props .maxidx ); 937 938if (table_props .maxidx == 0 ) { 939lua_pop (lstate ,1 ); 940return ret ; 941 } 942 943for (size_t i = 1 ;i <=table_props .maxidx ;i ++ ) { 944Object val ; 945 946lua_rawgeti (lstate ,-1 , (int )i ); 947 948val = nlua_pop_Object (lstate , false,arena ,err ); 949if (ERROR_SET (err )) { 950lua_pop (lstate ,1 ); 951if (!arena ) { 952api_free_array (ret ); 953 } 954return (Array ) { .size = 0 , .items = NULL }; 955 } 956ADD_C (ret ,val ); 957 } 958lua_pop (lstate ,1 ); 959 960return ret ; 961} 962 963/// Convert Lua table to array 964/// 965/// Always pops one value from the stack. 966Array nlua_pop_Array (lua_State * lstate ,Arena * arena ,Error * err ) 967FUNC_ATTR_NONNULL_ARG (1 ,3 )FUNC_ATTR_WARN_UNUSED_RESULT 968{ 969const LuaTableProps table_props = nlua_check_type (lstate ,err ,kObjectTypeArray ); 970if (table_props .type != kObjectTypeArray ) { 971return (Array ) { .size = 0 , .items = NULL }; 972 } 973return nlua_pop_Array_unchecked (lstate ,table_props ,arena ,err ); 974} 975 976/// Convert Lua table to dictionary 977/// 978/// Always pops one value from the stack. Does not check whether topmost 979/// value on the stack is a table. 980/// 981/// @param lstate Lua interpreter state. 982/// @param[in] table_props nlua_traverse_table() output. 983/// @param[out] err Location where error will be saved. 984static Dict nlua_pop_Dict_unchecked (lua_State * lstate ,const LuaTableProps table_props ,bool ref , 985Arena * arena ,Error * err ) 986FUNC_ATTR_NONNULL_ARG (1 ,5 )FUNC_ATTR_WARN_UNUSED_RESULT 987{ 988Dict ret = arena_dict (arena ,table_props .string_keys_num ); 989 990if (table_props .string_keys_num == 0 ) { 991lua_pop (lstate ,1 ); 992return ret ; 993 } 994 995lua_pushnil (lstate ); 996for (size_t i = 0 ;lua_next (lstate ,-2 )&& i < table_props .string_keys_num ;) { 997// stack: dict, key, value 998 999if (lua_type (lstate ,-2 )== LUA_TSTRING ) { 1000lua_pushvalue (lstate ,-2 ); 1001// stack: dict, key, value, key 1002 1003String key = nlua_pop_String (lstate ,arena ,err ); 1004// stack: dict, key, value 1005 1006if (!ERROR_SET (err )) { 1007Object value = nlua_pop_Object (lstate ,ref ,arena ,err ); 1008kv_push_c (ret , ((KeyValuePair ) { .key = key , .value = value })); 1009// stack: dict, key 1010 }else { 1011lua_pop (lstate ,1 ); 1012// stack: dict, key 1013 } 1014 1015if (ERROR_SET (err )) { 1016if (!arena ) { 1017api_free_dict (ret ); 1018 } 1019lua_pop (lstate ,2 ); 1020// stack: 1021return (Dict ) { .size = 0 , .items = NULL }; 1022 } 1023i ++ ; 1024 }else { 1025lua_pop (lstate ,1 ); 1026// stack: dict, key 1027 } 1028 } 1029lua_pop (lstate ,1 ); 1030 1031return ret ; 1032} 1033 1034/// Convert Lua table to dictionary 1035/// 1036/// Always pops one value from the stack. 1037Dict nlua_pop_Dict (lua_State * lstate ,bool ref ,Arena * arena ,Error * err ) 1038FUNC_ATTR_NONNULL_ARG (1 ,4 )FUNC_ATTR_WARN_UNUSED_RESULT 1039{ 1040const LuaTableProps table_props = nlua_check_type (lstate ,err , 1041kObjectTypeDict ); 1042if (table_props .type != kObjectTypeDict ) { 1043lua_pop (lstate ,1 ); 1044return (Dict ) { .size = 0 , .items = NULL }; 1045 } 1046 1047return nlua_pop_Dict_unchecked (lstate ,table_props ,ref ,arena ,err ); 1048} 1049 1050/// Helper structure for nlua_pop_Object 1051typedef struct { 1052Object * obj ;///< Location where conversion result is saved. 1053bool container ;///< True if tv is a container. 1054}ObjPopStackItem ; 1055 1056/// Convert Lua table to object 1057/// 1058/// Always pops one value from the stack. 1059Object nlua_pop_Object (lua_State * const lstate ,bool ref ,Arena * arena ,Error * const err ) 1060FUNC_ATTR_NONNULL_ARG (1 ,4 )FUNC_ATTR_WARN_UNUSED_RESULT 1061{ 1062Object ret = NIL ; 1063const int initial_size = lua_gettop (lstate ); 1064kvec_withinit_t (ObjPopStackItem ,2 )stack = KV_INITIAL_VALUE ; 1065kvi_init (stack ); 1066kvi_push (stack , ((ObjPopStackItem ){ .obj = & ret })); 1067while (!ERROR_SET (err )&& kv_size (stack )) { 1068ObjPopStackItem cur = kv_pop (stack ); 1069if (cur .container ) { 1070if (!lua_checkstack (lstate ,lua_gettop (lstate )+ 3 )) { 1071api_set_error (err ,kErrorTypeException ,"Lua failed to grow stack" ); 1072break ; 1073 } 1074if (cur .obj -> type == kObjectTypeDict ) { 1075// stack: …, dict, key 1076if (cur .obj -> data .dict .size == cur .obj -> data .dict .capacity ) { 1077lua_pop (lstate ,2 ); 1078continue ; 1079 } 1080bool next_key_found = false; 1081while (lua_next (lstate ,-2 )) { 1082// stack: …, dict, new key, val 1083if (lua_type (lstate ,-2 )== LUA_TSTRING ) { 1084next_key_found = true; 1085break ; 1086 } 1087lua_pop (lstate ,1 ); 1088// stack: …, dict, new key 1089 } 1090if (next_key_found ) { 1091// stack: …, dict, new key, val 1092size_t len ; 1093const char * s = lua_tolstring (lstate ,-2 ,& len ); 1094const size_t idx = cur .obj -> data .dict .size ++ ; 1095cur .obj -> data .dict .items [idx ].key = CBUF_TO_ARENA_STR (arena ,s ,len ); 1096kvi_push (stack ,cur ); 1097cur = (ObjPopStackItem ){ .obj = & cur .obj -> data .dict .items [idx ].value }; 1098 }else { 1099// stack: …, dict 1100lua_pop (lstate ,1 ); 1101// stack: … 1102continue ; 1103 } 1104 }else { 1105if (cur .obj -> data .array .size == cur .obj -> data .array .capacity ) { 1106lua_pop (lstate ,1 ); 1107continue ; 1108 } 1109const size_t idx = cur .obj -> data .array .size ++ ; 1110lua_rawgeti (lstate ,-1 , (int )idx + 1 ); 1111kvi_push (stack ,cur ); 1112cur = (ObjPopStackItem ){ .obj = & cur .obj -> data .array .items [idx ] }; 1113 } 1114 } 1115assert (!cur .container ); 1116* cur .obj = NIL ; 1117switch (lua_type (lstate ,-1 )) { 1118case LUA_TNIL : 1119break ; 1120case LUA_TBOOLEAN : 1121* cur .obj = BOOLEAN_OBJ (lua_toboolean (lstate ,-1 )); 1122break ; 1123case LUA_TSTRING : { 1124size_t len ; 1125const char * s = lua_tolstring (lstate ,-1 ,& len ); 1126* cur .obj = STRING_OBJ (CBUF_TO_ARENA_STR (arena ,s ,len )); 1127break ; 1128 } 1129case LUA_TNUMBER : { 1130const lua_Number n = lua_tonumber (lstate ,-1 ); 1131if (n > (lua_Number )API_INTEGER_MAX || n < (lua_Number )API_INTEGER_MIN 1132|| ((lua_Number )((Integer )n ))!= n ) { 1133* cur .obj = FLOAT_OBJ ((Float )n ); 1134 }else { 1135* cur .obj = INTEGER_OBJ ((Integer )n ); 1136 } 1137break ; 1138 } 1139case LUA_TTABLE : { 1140const LuaTableProps table_props = nlua_traverse_table (lstate ); 1141 1142switch (table_props .type ) { 1143case kObjectTypeArray : 1144* cur .obj = ARRAY_OBJ (((Array )ARRAY_DICT_INIT )); 1145if (table_props .maxidx != 0 ) { 1146cur .obj -> data .array = arena_array (arena ,table_props .maxidx ); 1147cur .container = true; 1148assert (kv_size (stack )< SIZE_MAX ); 1149kvi_push (stack ,cur ); 1150 } 1151break ; 1152case kObjectTypeDict : 1153* cur .obj = DICT_OBJ (((Dict )ARRAY_DICT_INIT )); 1154if (table_props .string_keys_num != 0 ) { 1155cur .obj -> data .dict = arena_dict (arena ,table_props .string_keys_num ); 1156cur .container = true; 1157assert (kv_size (stack )< SIZE_MAX ); 1158kvi_push (stack ,cur ); 1159lua_pushnil (lstate ); 1160 } 1161break ; 1162case kObjectTypeFloat : 1163* cur .obj = FLOAT_OBJ ((Float )table_props .val ); 1164break ; 1165case kObjectTypeNil : 1166api_set_error (err ,kErrorTypeValidation , 1167"Cannot convert given Lua table" ); 1168break ; 1169default : 1170abort (); 1171 } 1172break ; 1173 } 1174 1175case LUA_TFUNCTION : 1176if (ref ) { 1177* cur .obj = LUAREF_OBJ (nlua_ref_global (lstate ,-1 )); 1178 }else { 1179 gototype_error ; 1180 } 1181break ; 1182 1183case LUA_TUSERDATA : { 1184nlua_pushref (lstate ,nlua_global_refs -> nil_ref ); 1185bool is_nil = lua_rawequal (lstate ,-2 ,-1 ); 1186lua_pop (lstate ,1 ); 1187if (is_nil ) { 1188* cur .obj = NIL ; 1189 }else { 1190api_set_error (err ,kErrorTypeValidation ,"Cannot convert userdata" ); 1191 } 1192break ; 1193 } 1194 1195default : 1196type_error : 1197api_set_error (err ,kErrorTypeValidation ,"Cannot convert given Lua type" ); 1198break ; 1199 } 1200if (!cur .container ) { 1201lua_pop (lstate ,1 ); 1202 } 1203 } 1204kvi_destroy (stack ); 1205if (ERROR_SET (err )) { 1206if (!arena ) { 1207api_free_object (ret ); 1208 } 1209ret = NIL ; 1210lua_pop (lstate ,lua_gettop (lstate )- initial_size + 1 ); 1211 } 1212assert (lua_gettop (lstate )== initial_size - 1 ); 1213return ret ; 1214} 1215 1216LuaRef nlua_pop_LuaRef (lua_State * const lstate ,Arena * arena ,Error * err ) 1217{ 1218LuaRef rv = nlua_ref_global (lstate ,-1 ); 1219lua_pop (lstate ,1 ); 1220return rv ; 1221} 1222 1223handle_T nlua_pop_handle (lua_State * lstate ,Arena * arena ,Error * err ) 1224FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1225{ 1226handle_T ret ; 1227if (lua_type (lstate ,-1 )!= LUA_TNUMBER ) { 1228api_set_error (err ,kErrorTypeValidation ,"Expected Lua number" ); 1229ret = (handle_T )(-1 ); 1230 }else { 1231ret = (handle_T )lua_tonumber (lstate ,-1 ); 1232 } 1233lua_pop (lstate ,1 ); 1234return ret ; 1235} 1236 1237/// Record some auxiliary values in vim module 1238/// 1239/// Assumes that module table is on top of the stack. 1240/// 1241/// Recorded values: 1242/// 1243/// `vim.type_idx`: @see nlua_push_type_idx() 1244/// `vim.val_idx`: @see nlua_push_val_idx() 1245/// `vim.types`: table mapping possible values of `vim.type_idx` to string 1246/// names (i.e. `array`, `float`, `dictionary`) and back. 1247void nlua_init_types (lua_State * const lstate ) 1248{ 1249LUA_PUSH_STATIC_STRING (lstate ,"type_idx" ); 1250nlua_push_type_idx (lstate ); 1251lua_rawset (lstate ,-3 ); 1252 1253LUA_PUSH_STATIC_STRING (lstate ,"val_idx" ); 1254nlua_push_val_idx (lstate ); 1255lua_rawset (lstate ,-3 ); 1256 1257LUA_PUSH_STATIC_STRING (lstate ,"types" ); 1258lua_createtable (lstate ,0 ,3 ); 1259 1260LUA_PUSH_STATIC_STRING (lstate ,"float" ); 1261lua_pushnumber (lstate , (lua_Number )kObjectTypeFloat ); 1262lua_rawset (lstate ,-3 ); 1263lua_pushnumber (lstate , (lua_Number )kObjectTypeFloat ); 1264LUA_PUSH_STATIC_STRING (lstate ,"float" ); 1265lua_rawset (lstate ,-3 ); 1266 1267LUA_PUSH_STATIC_STRING (lstate ,"array" ); 1268lua_pushnumber (lstate , (lua_Number )kObjectTypeArray ); 1269lua_rawset (lstate ,-3 ); 1270lua_pushnumber (lstate , (lua_Number )kObjectTypeArray ); 1271LUA_PUSH_STATIC_STRING (lstate ,"array" ); 1272lua_rawset (lstate ,-3 ); 1273 1274LUA_PUSH_STATIC_STRING (lstate ,"dictionary" ); 1275lua_pushnumber (lstate , (lua_Number )kObjectTypeDict ); 1276lua_rawset (lstate ,-3 ); 1277lua_pushnumber (lstate , (lua_Number )kObjectTypeDict ); 1278LUA_PUSH_STATIC_STRING (lstate ,"dictionary" ); 1279lua_rawset (lstate ,-3 ); 1280 1281lua_rawset (lstate ,-3 ); 1282} 1283 1284// Lua specific variant of api_dict_to_keydict 1285void nlua_pop_keydict (lua_State * L ,void * retval ,FieldHashfn hashy ,char ** err_opt ,Arena * arena , 1286Error * err ) 1287{ 1288if (!lua_istable (L ,-1 )) { 1289api_set_error (err ,kErrorTypeValidation ,"Expected Lua table" ); 1290lua_pop (L ,-1 ); 1291return ; 1292 } 1293 1294lua_pushnil (L );// [dict, nil] 1295while (lua_next (L ,-2 )) { 1296// [dict, key, value] 1297size_t len ; 1298const char * s = lua_tolstring (L ,-2 ,& len ); 1299const KeySetLink * field = hashy (s ,len ); 1300if (!field ) { 1301api_set_error (err ,kErrorTypeValidation ,"invalid key: %.*s" , (int )len ,s ); 1302lua_pop (L ,3 );// [] 1303return ; 1304 } 1305 1306if (field -> opt_index >=0 ) { 1307OptKeySet * ks = (OptKeySet * )retval ; 1308ks -> is_set_ |= (1ULL <<field -> opt_index ); 1309 } 1310char * mem = ((char * )retval + field -> ptr_off ); 1311 1312if (field -> type == kObjectTypeNil ) { 1313* (Object * )mem = nlua_pop_Object (L , true,arena ,err ); 1314 }else if (field -> type == kObjectTypeInteger ) { 1315if (field -> is_hlgroup && lua_type (L ,-1 )== LUA_TSTRING ) { 1316size_t name_len ; 1317const char * name = lua_tolstring (L ,-1 ,& name_len ); 1318lua_pop (L ,1 ); 1319* (Integer * )mem = name_len > 0 ?syn_check_group (name ,name_len ) :0 ; 1320 }else { 1321* (Integer * )mem = nlua_pop_Integer (L ,arena ,err ); 1322 } 1323 }else if (field -> type == kObjectTypeBoolean ) { 1324* (Boolean * )mem = nlua_pop_Boolean_strict (L ,err ); 1325 }else if (field -> type == kObjectTypeString ) { 1326* (String * )mem = nlua_pop_String (L ,arena ,err ); 1327 }else if (field -> type == kObjectTypeFloat ) { 1328* (Float * )mem = nlua_pop_Float (L ,arena ,err ); 1329 }else if (field -> type == kObjectTypeBuffer || field -> type == kObjectTypeWindow 1330|| field -> type == kObjectTypeTabpage ) { 1331* (handle_T * )mem = nlua_pop_handle (L ,arena ,err ); 1332 }else if (field -> type == kObjectTypeArray ) { 1333* (Array * )mem = nlua_pop_Array (L ,arena ,err ); 1334 }else if (field -> type == kObjectTypeDict ) { 1335* (Dict * )mem = nlua_pop_Dict (L , false,arena ,err ); 1336 }else if (field -> type == kObjectTypeLuaRef ) { 1337* (LuaRef * )mem = nlua_pop_LuaRef (L ,arena ,err ); 1338 }else { 1339abort (); 1340 } 1341if (ERROR_SET (err )) { 1342* err_opt = field -> str ; 1343break ; 1344 } 1345 } 1346// [dict] 1347lua_pop (L ,1 ); 1348// [] 1349} 1350 1351void nlua_push_keydict (lua_State * L ,void * value ,KeySetLink * table ) 1352{ 1353lua_createtable (L ,0 ,0 ); 1354for (size_t i = 0 ;table [i ].str ;i ++ ) { 1355KeySetLink * field = & table [i ]; 1356bool is_set = true; 1357if (field -> opt_index >=0 ) { 1358OptKeySet * ks = (OptKeySet * )value ; 1359is_set = ks -> is_set_ & (1ULL <<field -> opt_index ); 1360 } 1361 1362if (!is_set ) { 1363continue ; 1364 } 1365 1366char * mem = ((char * )value + field -> ptr_off ); 1367 1368lua_pushstring (L ,field -> str ); 1369if (field -> type == kObjectTypeNil ) { 1370nlua_push_Object (L , (Object * )mem ,0 ); 1371 }else if (field -> type == kObjectTypeInteger ) { 1372lua_pushinteger (L ,* (Integer * )mem ); 1373 }else if (field -> type == kObjectTypeBuffer || field -> type == kObjectTypeWindow 1374|| field -> type == kObjectTypeTabpage ) { 1375lua_pushinteger (L ,* (handle_T * )mem ); 1376 }else if (field -> type == kObjectTypeFloat ) { 1377lua_pushnumber (L ,* (Float * )mem ); 1378 }else if (field -> type == kObjectTypeBoolean ) { 1379lua_pushboolean (L ,* (Boolean * )mem ); 1380 }else if (field -> type == kObjectTypeString ) { 1381nlua_push_String (L ,* (String * )mem ,0 ); 1382 }else if (field -> type == kObjectTypeArray ) { 1383nlua_push_Array (L ,* (Array * )mem ,0 ); 1384 }else if (field -> type == kObjectTypeDict ) { 1385nlua_push_Dict (L ,* (Dict * )mem ,0 ); 1386 }else if (field -> type == kObjectTypeLuaRef ) { 1387nlua_pushref (L ,* (LuaRef * )mem ); 1388 }else { 1389abort (); 1390 } 1391 1392lua_rawset (L ,-3 ); 1393 } 1394}