robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1#include <assert.h> 2#include <inttypes.h> 3#include <lauxlib.h> 4#include <lua.h> 5#include <lualib.h> 6#include <math.h> 7#include <stddef.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11#include <tree_sitter/api.h> 12#include <uv.h> 13 14#include "klib/kvec.h" 15#include "luv/luv.h" 16#include "nvim/api/extmark.h" 17#include "nvim/api/private/defs.h" 18#include "nvim/api/private/helpers.h" 19#include "nvim/api/ui.h" 20#include "nvim/ascii_defs.h" 21#include "nvim/buffer_defs.h" 22#include "nvim/change.h" 23#include "nvim/channel.h" 24#include "nvim/cmdexpand_defs.h" 25#include "nvim/cursor.h" 26#include "nvim/drawscreen.h" 27#include "nvim/errors.h" 28#include "nvim/eval/funcs.h" 29#include "nvim/eval/typval.h" 30#include "nvim/eval/typval_defs.h" 31#include "nvim/eval/userfunc.h" 32#include "nvim/event/defs.h" 33#include "nvim/event/loop.h" 34#include "nvim/event/multiqueue.h" 35#include "nvim/event/time.h" 36#include "nvim/ex_cmds.h" 37#include "nvim/ex_cmds_defs.h" 38#include "nvim/ex_docmd.h" 39#include "nvim/ex_getln.h" 40#include "nvim/garray.h" 41#include "nvim/garray_defs.h" 42#include "nvim/gettext_defs.h" 43#include "nvim/globals.h" 44#include "nvim/input.h" 45#include "nvim/keycodes.h" 46#include "nvim/lua/converter.h" 47#include "nvim/lua/executor.h" 48#include "nvim/lua/stdlib.h" 49#include "nvim/lua/treesitter.h" 50#include "nvim/macros_defs.h" 51#include "nvim/main.h" 52#include "nvim/mbyte_defs.h" 53#include "nvim/memline.h" 54#include "nvim/memory.h" 55#include "nvim/memory_defs.h" 56#include "nvim/message.h" 57#include "nvim/message_defs.h" 58#include "nvim/msgpack_rpc/channel.h" 59#include "nvim/option_vars.h" 60#include "nvim/os/fileio.h" 61#include "nvim/os/fileio_defs.h" 62#include "nvim/os/os.h" 63#include "nvim/path.h" 64#include "nvim/pos_defs.h" 65#include "nvim/profile.h" 66#include "nvim/runtime.h" 67#include "nvim/runtime_defs.h" 68#include "nvim/strings.h" 69#include "nvim/ui.h" 70#include "nvim/ui_defs.h" 71#include "nvim/undo.h" 72#include "nvim/usercmd.h" 73#include "nvim/vim_defs.h" 74#include "nvim/window.h" 75 76#ifndef MSWIN 77# include <pthread.h> 78#endif 79 80static int in_fast_callback = 0 ; 81 82// Initialized in nlua_init(). 83static lua_State * global_lstate = NULL ; 84 85// Tracks the currently executing Lua thread (main or coroutine). 86lua_State * active_lstate = NULL ; 87 88static LuaRef require_ref = LUA_REFNIL ; 89 90static uv_thread_t main_thread ; 91 92typedef struct { 93Error err ; 94String lua_err_str ; 95}LuaError ; 96 97typedef struct { 98char * name ; 99const uint8_t * data ; 100size_t size ; 101}ModuleDef ; 102 103typedef struct { 104LuaRef getline ;///< Lua function returning the next input line, or nil at EOF. 105bool got_line ;///< True if at least one line was read. 106}ExDocmdCookie ; 107 108#include "lua/executor.c.generated.h" 109#include "lua/vim_module.generated.h" 110 111#define PUSH_ALL_TYPVALS (lstate ,args ,argcount ,special ) \ 112 for (int i = 0; i < argcount; i++) { \ 113 if (args[i].v_type == VAR_UNKNOWN) { \ 114 lua_pushnil(lstate); \ 115 } else { \ 116 nlua_push_typval(lstate, &args[i], (special) ? kNluaPushSpecial : 0); \ 117 } \ 118 } 119 120/// Pushes cmdmod_T as a table (Lua type: `vim.api.keyset.cmd_mods_ret`) onto the stack. 121static void nlua_push_cmdmod (lua_State * lstate ,const cmdmod_T * cmod ) 122{ 123lua_newtable (lstate ); 124 125lua_pushinteger (lstate ,cmod -> cmod_tab - 1 ); 126lua_setfield (lstate ,-2 ,"tab" ); 127 128lua_pushinteger (lstate ,cmod -> cmod_verbose - 1 ); 129lua_setfield (lstate ,-2 ,"verbose" ); 130 131if (cmod -> cmod_split & WSP_ABOVE ) { 132lua_pushstring (lstate ,"aboveleft" ); 133 }else if (cmod -> cmod_split & WSP_BELOW ) { 134lua_pushstring (lstate ,"belowright" ); 135 }else if (cmod -> cmod_split & WSP_TOP ) { 136lua_pushstring (lstate ,"topleft" ); 137 }else if (cmod -> cmod_split & WSP_BOT ) { 138lua_pushstring (lstate ,"botright" ); 139 }else { 140lua_pushstring (lstate ,"" ); 141 } 142lua_setfield (lstate ,-2 ,"split" ); 143 144lua_pushboolean (lstate ,cmod -> cmod_split & WSP_VERT ); 145lua_setfield (lstate ,-2 ,"vertical" ); 146lua_pushboolean (lstate ,cmod -> cmod_split & WSP_HOR ); 147lua_setfield (lstate ,-2 ,"horizontal" ); 148lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_SILENT ); 149lua_setfield (lstate ,-2 ,"silent" ); 150lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_ERRSILENT ); 151lua_setfield (lstate ,-2 ,"emsg_silent" ); 152lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_UNSILENT ); 153lua_setfield (lstate ,-2 ,"unsilent" ); 154lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_SANDBOX ); 155lua_setfield (lstate ,-2 ,"sandbox" ); 156lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_NOAUTOCMD ); 157lua_setfield (lstate ,-2 ,"noautocmd" ); 158lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_BROWSE ); 159lua_setfield (lstate ,-2 ,"browse" ); 160lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_CONFIRM ); 161lua_setfield (lstate ,-2 ,"confirm" ); 162lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_HIDE ); 163lua_setfield (lstate ,-2 ,"hide" ); 164lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_KEEPALT ); 165lua_setfield (lstate ,-2 ,"keepalt" ); 166lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_KEEPJUMPS ); 167lua_setfield (lstate ,-2 ,"keepjumps" ); 168lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_KEEPMARKS ); 169lua_setfield (lstate ,-2 ,"keepmarks" ); 170lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_KEEPPATTERNS ); 171lua_setfield (lstate ,-2 ,"keeppatterns" ); 172lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_LOCKMARKS ); 173lua_setfield (lstate ,-2 ,"lockmarks" ); 174lua_pushboolean (lstate ,cmod -> cmod_flags & CMOD_NOSWAPFILE ); 175lua_setfield (lstate ,-2 ,"noswapfile" ); 176 177// ":filter[!] /pattern/" modifier (same shape as `nvim_parse_cmd().mods.filter`). 178lua_newtable (lstate ); 179lua_pushstring (lstate ,cmod -> cmod_filter_pat ?cmod -> cmod_filter_pat :"" ); 180lua_setfield (lstate ,-2 ,"pattern" ); 181lua_pushboolean (lstate ,cmod -> cmod_filter_force ); 182lua_setfield (lstate ,-2 ,"force" ); 183lua_setfield (lstate ,-2 ,"filter" ); 184} 185 186/// Pushes common exarg_T fields (bang, line1, line2, …) onto a table at the top of the stack. 187static void nlua_push_eap (lua_State * lstate ,exarg_T * eap ,const cmdmod_T * cmod ) 188{ 189// Canonical name (for builtin cmds); for usercmds `nlua_do_ucmd` sets "name" to the user-defined name. 190if (!IS_USER_CMDIDX (eap -> cmdidx )&& eap -> cmdidx < CMD_SIZE ) { 191lua_pushstring (lstate ,get_command_name (NULL ,eap -> cmdidx )); 192lua_setfield (lstate ,-2 ,"name" ); 193 } 194 195// Modifier string (e.g. ":vert silent"). Same content as `nvim_parse_cmd().mods`. 196// Useful when forwarding the command verbatim, e.g. `feedkeys('<Cmd>'..eap.mods..' …<CR>')`. 197// 198// The size is chosen empirically to hold every modifier with room to spare; bump if more are added. 199char mods_buf [200 ]= {0 }; 200uc_mods (mods_buf ,cmod , false); 201lua_pushstring (lstate ,mods_buf ); 202lua_setfield (lstate ,-2 ,"mods" ); 203 204// Structured form of `mods`. 205nlua_push_cmdmod (lstate ,cmod ); 206lua_setfield (lstate ,-2 ,"smods" ); 207 208lua_pushstring (lstate ,eap -> arg ); 209lua_setfield (lstate ,-2 ,"args" ); 210 211lua_pushboolean (lstate ,eap -> forceit ); 212lua_setfield (lstate ,-2 ,"bang" ); 213 214lua_pushinteger (lstate ,eap -> line1 ); 215lua_setfield (lstate ,-2 ,"line1" ); 216 217lua_pushinteger (lstate ,eap -> line2 ); 218lua_setfield (lstate ,-2 ,"line2" ); 219 220lua_pushinteger (lstate ,eap -> addr_count ); 221lua_setfield (lstate ,-2 ,"range" ); 222 223lua_pushinteger (lstate ,eap -> line2 ); 224lua_setfield (lstate ,-2 ,"count" ); 225 226char reg [2 ]= { (char )eap -> regname ,NUL }; 227lua_pushstring (lstate ,reg ); 228lua_setfield (lstate ,-2 ,"reg" ); 229 230// Push pre-split args as "fargs" list, if available (set by the command-line parser). 231// - Or fall back to splitting `eap->arg` on unescaped whitespace. 232// - Usercmds with nargs=1/? need different splitting, handled by `nlua_do_ucmd`. 233if (eap -> args != NULL ) { 234lua_createtable (lstate , (int )eap -> argc ,0 ); 235for (size_t i = 0 ;i < eap -> argc ;i ++ ) { 236lua_pushlstring (lstate ,eap -> args [i ],eap -> arglens [i ]); 237lua_rawseti (lstate ,-2 , (int )i + 1 ); 238 } 239lua_setfield (lstate ,-2 ,"fargs" ); 240 }else { 241lua_newtable (lstate ); 242size_t length = strlen (eap -> arg ); 243if (length > 0 ) { 244size_t end = 0 ; 245size_t len = 0 ; 246int i = 1 ; 247char * buf = xcalloc (length ,sizeof (char )); 248bool done = false; 249while (!done ) { 250done = uc_split_args_iter (eap -> arg ,length ,& end ,buf ,& len ); 251if (len > 0 ) { 252lua_pushlstring (lstate ,buf ,len ); 253lua_rawseti (lstate ,-2 ,i ); 254i ++ ; 255 } 256 } 257xfree (buf ); 258 } 259lua_setfield (lstate ,-2 ,"fargs" ); 260 } 261} 262 263#if __has_feature (address_sanitizer ) 264static bool nlua_track_refs = false; 265# define NLUA_TRACK_REFS 266#endif 267 268typedef enum luv_err_type { 269kCallback , 270kThread , 271kThreadCallback , 272}luv_err_t ; 273 274lua_State * get_global_lstate (void ) 275{ 276return global_lstate ; 277} 278 279/// Gets the Lua error at top of stack as a string, possibly modifying it in-place (but doesn't 280/// change stack height). 281/// 282/// The returned string points to memory on the Lua stack. Use or duplicate it before using 283/// `lstate` again. 284/// 285/// @param[out] len length of error 286static const char * nlua_get_error (lua_State * lstate ,size_t * len ) 287FUNC_ATTR_NONNULL_RET 288{ 289if (lua_type (lstate ,-1 )!= LUA_TSTRING ) { 290lua_getglobal (lstate ,"tostring" ); 291lua_pushvalue (lstate ,-2 ); 292if (lua_pcall (lstate ,1 ,1 ,0 )|| lua_type (lstate ,-1 )!= LUA_TSTRING ) { 293lua_pop (lstate ,1 ); 294lua_pushstring (lstate ,"[UNPRINTABLE ERROR]" ); 295 } 296lua_replace (lstate ,-2 ); 297 } 298 299return lua_tolstring (lstate ,-1 ,len ); 300} 301 302/// Converts a Lua error into a Vim error message. 303/// 304/// @param lstate Lua interpreter state. 305/// @param[in] msg Message base, must contain one `%.*s`. 306void nlua_error (lua_State * const lstate ,const char * const msg ) 307FUNC_ATTR_NONNULL_ALL 308{ 309size_t len ; 310const char * str = nlua_get_error (lstate ,& len ); 311 312msg_ext_no_fast (); 313semsg_multiline ("lua_error" ,msg , (int )len ,str ); 314 315lua_pop (lstate ,1 ); 316} 317 318/// Dummy errfunc used if `_G.debug.traceback` is broken: returns the error object unchanged. 319static int nlua_no_traceback (lua_State * lstate ) 320{ 321return 1 ; 322} 323 324/// Like lua_pcall, but use `debug.traceback` as errfunc. Called by most Lua entrypoints (`:lua`, 325/// `luaeval()`, `v:lua`, API calls, …). Not used by `pcall()` itself. 326/// 327/// @param lstate Lua interpreter state 328/// @param[in] nargs Number of arguments expected by the function being called. 329/// @param[in] nresults Number of results the function returns. 330int nlua_pcall (lua_State * lstate ,int nargs ,int nresults ) 331{ 332// Detect broken `_G.debug` (by user code). #41504 333lua_getglobal (lstate ,"debug" ); 334if (lua_istable (lstate ,-1 )) { 335lua_getfield (lstate ,-1 ,"traceback" ); 336lua_remove (lstate ,-2 ); 337 } 338bool no_traceback = !lua_isfunction (lstate ,-1 );// `_G.debug.traceback` is a function? 339if (no_traceback ) { 340lua_pop (lstate ,1 ); 341lua_pushcfunction (lstate ,nlua_no_traceback ); 342 } 343lua_insert (lstate ,-2 - nargs ); 344int pre_top = lua_gettop (lstate ); 345int status = lua_pcall (lstate ,nargs ,nresults ,-2 - nargs ); 346if (status ) { 347lua_remove (lstate ,-2 ); 348if (no_traceback && status == LUA_ERRRUN && lua_isstring (lstate ,-1 )) { 349lua_pushliteral (lstate ,"\nNo traceback: debug.traceback is not a function" ); 350lua_concat (lstate ,2 ); 351 } 352 }else { 353if (nresults == LUA_MULTRET ) { 354nresults = lua_gettop (lstate )- (pre_top - nargs - 1 ); 355 } 356lua_remove (lstate ,-1 - nresults ); 357 } 358return status ; 359} 360 361static void nlua_luv_error_event (void ** argv ) 362{ 363char * error = (char * )argv [0 ]; 364luv_err_t type = (luv_err_t )(intptr_t )argv [1 ]; 365switch (type ) { 366case kCallback : 367msg_ext_no_fast (); 368semsg_multiline ("lua_error" ,"Lua callback:\n%s" ,error ); 369break ; 370case kThread : 371semsg_multiline ("lua_error" ,"Luv thread:\n%s" ,error ); 372break ; 373case kThreadCallback : 374semsg_multiline ("lua_error" ,"Luv callback, thread:\n%s" ,error ); 375break ; 376default : 377break ; 378 } 379xfree (error ); 380} 381 382/// Execute callback in "fast" context. Used for luv and some vim.ui_event 383/// callbacks where using the API directly is not safe. 384static int nlua_fast_cfpcall (lua_State * lstate ,int nargs ,int nresult ,int flags ) 385FUNC_ATTR_NONNULL_ALL 386{ 387int retval ; 388 389in_fast_callback ++ ; 390 391int top = lua_gettop (lstate ); 392int status = nlua_pcall (lstate ,nargs ,nresult ); 393if (status ) { 394if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT )) { 395// consider out of memory errors unrecoverable, just like xmalloc() 396preserve_exit (e_outofmem ); 397 } 398 399size_t len ; 400const char * error = nlua_get_error (lstate ,& len ); 401 402multiqueue_put (main_loop .events ,nlua_luv_error_event , 403error != NULL ?xstrdup (error ) :NULL , (void * )(intptr_t )kCallback ); 404lua_pop (lstate ,1 );// error message 405retval = - status ; 406 }else {// LUA_OK 407if (nresult == LUA_MULTRET ) { 408nresult = lua_gettop (lstate )- top + nargs + 1 ; 409 } 410retval = nresult ; 411 } 412 413in_fast_callback -- ; 414return retval ; 415} 416 417static int nlua_luv_thread_cb_cfpcall (lua_State * lstate ,int nargs ,int nresult ,int flags ) 418{ 419return nlua_luv_thread_common_cfpcall (lstate ,nargs ,nresult ,flags , true); 420} 421 422static int nlua_luv_thread_cfpcall (lua_State * lstate ,int nargs ,int nresult ,int flags ) 423FUNC_ATTR_NONNULL_ALL 424{ 425return nlua_luv_thread_common_cfpcall (lstate ,nargs ,nresult ,flags , false); 426} 427 428static int nlua_luv_thread_cfcpcall (lua_State * lstate ,lua_CFunction func ,void * ud ,int flags ) 429FUNC_ATTR_NONNULL_ARG (1 ,2 ) 430{ 431lua_pushcfunction (lstate ,func ); 432lua_pushlightuserdata (lstate ,ud ); 433int retval = nlua_luv_thread_cfpcall (lstate ,1 ,0 ,flags ); 434return retval ; 435} 436 437static int nlua_luv_thread_common_cfpcall (lua_State * lstate ,int nargs ,int nresult ,int flags , 438bool is_callback ) 439FUNC_ATTR_NONNULL_ALL 440{ 441int retval ; 442 443int top = lua_gettop (lstate ); 444int status = lua_pcall (lstate ,nargs ,nresult ,0 ); 445if (status ) { 446if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT )) { 447// Terminate this thread, as the main thread may be able to continue 448// execution. 449fprintf (stderr ,"%s\n" ,e_outofmem ); 450lua_close (lstate ); 451#ifdef MSWIN 452ExitThread (0 ); 453#else 454pthread_exit (0 ); 455#endif 456 } 457size_t len ; 458const char * error = nlua_get_error (lstate ,& len ); 459loop_schedule_deferred (& main_loop , 460event_create (nlua_luv_error_event , 461xmemdupz (error ,len ), 462 (void * )(intptr_t )(is_callback 463 ?kThreadCallback 464 :kThread ))); 465lua_pop (lstate ,1 );// error message 466retval = - status ; 467 }else {// LUA_OK 468if (nresult == LUA_MULTRET ) { 469nresult = lua_gettop (lstate )- top + nargs + 1 ; 470 } 471retval = nresult ; 472 } 473 474return retval ; 475} 476 477static int nlua_thr_api_nvim__get_runtime (lua_State * lstate ) 478{ 479if (lua_gettop (lstate )!= 3 ) { 480return luaL_error (lstate ,"Expected 3 arguments" ); 481 } 482 483luaL_checktype (lstate ,-1 ,LUA_TTABLE ); 484lua_getfield (lstate ,-1 ,"is_lua" ); 485if (!lua_isboolean (lstate ,-1 )) { 486return luaL_error (lstate ,"is_lua is not a boolean" ); 487 } 488bool is_lua = lua_toboolean (lstate ,-1 ); 489lua_pop (lstate ,2 ); 490 491luaL_checktype (lstate ,-1 ,LUA_TBOOLEAN ); 492bool all = lua_toboolean (lstate ,-1 ); 493lua_pop (lstate ,1 ); 494 495Error err = ERROR_INIT ; 496// TODO(bfredl): we could use an arena here for both "pat" and "ret", but then 497// we need a path to not use the freelist but a private block local to the thread. 498// We do not want mutex contentionery for the main arena freelist. 499const Array pat = nlua_pop_Array (lstate ,NULL ,& err ); 500if (ERROR_SET (& err )) { 501luaL_where (lstate ,1 ); 502lua_pushstring (lstate ,err .msg ); 503api_clear_error (& err ); 504lua_concat (lstate ,2 ); 505return lua_error (lstate ); 506 } 507 508ArrayOf (String )ret = runtime_get_named_thread (is_lua ,pat ,all ); 509nlua_push_Array (lstate ,ret ,kNluaPushSpecial ); 510api_free_array (ret ); 511api_free_array (pat ); 512 513return 1 ; 514} 515 516/// Copies args starting at `lua_arg0` to Lua `_G.arg`, and sets `_G.arg[0]` to the scriptname. 517/// 518/// Example (arg[0] => "foo.lua", arg[1] => "--arg1", …): 519/// nvim -l foo.lua --arg1 --arg2 520/// 521/// @note Lua CLI sets args before "-e" as _negative_ `_G.arg` indices, but we currently don't. 522/// 523/// @see https://www.lua.org/pil/1.4.html 524/// @see https://github.com/premake/premake-core/blob/1c1304637f4f5e50ba8c57aae8d1d80ec3b7aaf2/src/host/premake.c#L563-L594 525/// 526/// @returns number of args 527static int nlua_init_argv (lua_State * const L ,char ** argv ,int argc ,int lua_arg0 ) 528{ 529int i = 0 ; 530lua_newtable (L );// _G.arg 531 532if (lua_arg0 > 0 ) { 533lua_pushstring (L ,argv [lua_arg0 - 1 ]); 534lua_rawseti (L ,-2 ,0 );// _G.arg[0] = "foo.lua" 535 536for (;i + lua_arg0 < argc ;i ++ ) { 537lua_pushstring (L ,argv [i + lua_arg0 ]); 538lua_rawseti (L ,-2 ,i + 1 );// _G.arg[i+1] = "--foo" 539 } 540 } 541 542lua_setglobal (L ,"arg" ); 543return i ; 544} 545 546static void nlua_schedule_event (void ** argv ) 547{ 548LuaRef cb = (LuaRef )(ptrdiff_t )argv [0 ]; 549uint32_t ns_id = (uint32_t )(ptrdiff_t )argv [1 ]; 550lua_State * const lstate = global_lstate ; 551nlua_pushref (lstate ,cb ); 552nlua_unref_global (lstate ,cb ); 553 554// Don't impose textlock restrictions upon UI event handlers. 555int save_expr_map_lock = expr_map_lock ; 556int save_textlock = textlock ; 557expr_map_lock = ns_id > 0 ?0 :expr_map_lock ; 558textlock = ns_id > 0 ?0 :textlock ; 559if (nlua_pcall (lstate ,0 ,0 )) { 560nlua_error (lstate ,_ ("vim.schedule callback: %.*s" )); 561ui_remove_cb (ns_id , true); 562 } 563expr_map_lock = save_expr_map_lock ; 564textlock = save_textlock ; 565} 566 567/// Schedule Lua callback on main loop's event queue 568/// 569/// @param lstate Lua interpreter state. 570static int nlua_schedule (lua_State * const lstate ) 571FUNC_ATTR_NONNULL_ALL 572{ 573if (lua_type (lstate ,1 )!= LUA_TFUNCTION ) { 574lua_pushliteral (lstate ,"vim.schedule: expected function" ); 575return lua_error (lstate ); 576 } 577 578lua_pushnil (lstate ); 579// If main_loop is closing don't schedule tasks to run in the future, 580// otherwise any refs allocated here will not be cleaned up. 581if (main_loop .closing ) { 582lua_pushliteral (lstate ,"main loop is closing" ); 583return 2 ; 584 } 585 586LuaRef cb = nlua_ref_global (lstate ,1 ); 587// Pass along UI event handler to disable on error. 588multiqueue_put (main_loop .events ,nlua_schedule_event , (void * )(ptrdiff_t )cb , 589 (void * )(ptrdiff_t )ui_event_ns_id ); 590lua_pushnil (lstate ); 591return 2 ; 592} 593 594static int nlua_loop_poll (lua_State * lstate ) 595FUNC_ATTR_NONNULL_ALL 596{ 597int64_t timeout = (int64_t )luaL_checkinteger (lstate ,1 ); 598bool fast_only = lua_toboolean (lstate ,2 ); 599 600MultiQueue * loop_events = fast_only ?main_loop .fast_events :main_loop .events ; 601LOOP_PROCESS_EVENTS (& main_loop ,loop_events ,timeout ); 602 603return 0 ; 604} 605 606static int nlua_ui_flush (lua_State * lstate ) 607FUNC_ATTR_NONNULL_ALL 608{ 609ui_flush (); 610return 0 ; 611} 612 613static int nlua_check_interrupt (lua_State * lstate ) 614FUNC_ATTR_NONNULL_ALL 615{ 616bool interrupted = got_int ; 617if (got_int ) { 618got_int = false; 619vgetc (); 620 } 621 622lua_pushboolean (lstate ,interrupted ); 623return 1 ; 624} 625 626/// LineGetter for nlua_ex_docmd(): calls the Lua `getline` function. 627static char * nlua_ex_getline (int c ,void * cookie ,int indent ,bool do_concat ) 628{ 629ExDocmdCookie * ecd = cookie ; 630lua_State * lstate = global_lstate ; 631nlua_pushref (lstate ,ecd -> getline ); 632if (nlua_pcall (lstate ,0 ,1 )) { 633nlua_error (lstate ,_ ("Error executing Ex-mode line getter: %.*s" )); 634return NULL ; 635 } 636if (lua_type (lstate ,-1 )!= LUA_TSTRING ) {// nil: EOF. 637lua_pop (lstate ,1 ); 638return NULL ; 639 } 640char * line = xstrdup (lua_tostring (lstate ,-1 )); 641lua_pop (lstate ,1 ); 642ecd -> got_line = true; 643return line ; 644} 645 646/// For exmode.lua: Executes one cmdline obtained from `getline`, which is also called for any 647/// continuation lines (`:append` text, `:function` body, heredoc, …). Unlike `nvim_exec2()`, errors 648/// are emitted (not thrown), so the caller can continue with the next command. #40966 649static int nlua_ex_docmd (lua_State * lstate ) 650FUNC_ATTR_NONNULL_ALL 651{ 652luaL_checktype (lstate ,1 ,LUA_TFUNCTION ); 653ExDocmdCookie cookie = { .getline = nlua_ref_global (lstate ,1 ) }; 654msg_scroll = true; 655need_wait_return = false; 656no_wait_return ++ ;// Don't wait for return, e.g. after "-V1" messages. 657do_cmdline (NULL ,nlua_ex_getline ,& cookie ,0 ); 658no_wait_return -- ; 659nlua_unref_global (lstate ,cookie .getline ); 660lua_pushboolean (lstate ,cookie .got_line ); 661return 1 ; 662} 663 664static int nlua_os_exit (lua_State * lstate ) 665{ 666if (in_fast_callback > 0 ) { 667return luaL_error (lstate ,e_fast_api_disabled ,"os.exit" ); 668 } 669 670int status = 0 ; 671if (lua_gettop (lstate ) >=1 && !lua_isnil (lstate ,1 )) { 672status = lua_isboolean (lstate ,1 ) ? (lua_toboolean (lstate ,1 ) ?0 :1 ) 673 : (int )luaL_checkinteger (lstate ,1 ); 674 } 675getout (status ); 676return 0 ;// Unreachable, but MSVC does not infer getout() is noreturn. 677} 678 679static nlua_ref_state_t * nlua_new_ref_state (lua_State * lstate ,bool is_thread ) 680FUNC_ATTR_NONNULL_ALL 681{ 682nlua_ref_state_t * ref_state = lua_newuserdata (lstate ,sizeof (* ref_state )); 683CLEAR_POINTER (ref_state ); 684ref_state -> nil_ref = LUA_NOREF ; 685ref_state -> empty_dict_ref = LUA_NOREF ; 686if (!is_thread ) { 687nlua_global_refs = ref_state ; 688 } 689return ref_state ; 690} 691 692static nlua_ref_state_t * nlua_get_ref_state (lua_State * lstate ) 693FUNC_ATTR_NONNULL_ALL 694{ 695lua_getfield (lstate ,LUA_REGISTRYINDEX ,"nlua.ref_state" ); 696nlua_ref_state_t * ref_state = lua_touserdata (lstate ,-1 ); 697lua_pop (lstate ,1 ); 698 699return ref_state ; 700} 701 702LuaRef nlua_get_nil_ref (lua_State * lstate ) 703FUNC_ATTR_NONNULL_ALL 704{ 705nlua_ref_state_t * ref_state = nlua_get_ref_state (lstate ); 706return ref_state -> nil_ref ; 707} 708 709LuaRef nlua_get_empty_dict_ref (lua_State * lstate ) 710FUNC_ATTR_NONNULL_ALL 711{ 712nlua_ref_state_t * ref_state = nlua_get_ref_state (lstate ); 713return ref_state -> empty_dict_ref ; 714} 715 716int nlua_get_global_ref_count (void ) 717{ 718return nlua_global_refs -> ref_count ; 719} 720 721static void nlua_common_vim_init (lua_State * lstate ,bool is_thread ) 722FUNC_ATTR_NONNULL_ARG (1 ) 723{ 724nlua_ref_state_t * ref_state = nlua_new_ref_state (lstate ,is_thread ); 725lua_setfield (lstate ,LUA_REGISTRYINDEX ,"nlua.ref_state" ); 726 727// vim.is_thread 728lua_pushboolean (lstate ,is_thread ); 729lua_setfield (lstate ,LUA_REGISTRYINDEX ,"nvim.thread" ); 730lua_pushcfunction (lstate ,& nlua_is_thread ); 731lua_setfield (lstate ,-2 ,"is_thread" ); 732 733// vim._core 734lua_createtable (lstate ,0 ,0 ); 735lua_setfield (lstate ,-2 ,"_core" ); 736 737// vim.NIL 738lua_newuserdata (lstate ,0 ); 739lua_createtable (lstate ,0 ,0 ); 740lua_pushcfunction (lstate ,& nlua_nil_tostring ); 741lua_setfield (lstate ,-2 ,"__tostring" ); 742lua_pushcfunction (lstate ,& nlua_nil_index ); 743lua_setfield (lstate ,-2 ,"__index" ); 744lua_pushcfunction (lstate ,& nlua_nil_index ); 745lua_setfield (lstate ,-2 ,"__newindex" ); 746lua_setmetatable (lstate ,-2 ); 747ref_state -> nil_ref = nlua_ref (lstate ,ref_state ,-1 ); 748lua_pushvalue (lstate ,-1 ); 749lua_setfield (lstate ,LUA_REGISTRYINDEX ,"mpack.NIL" ); 750lua_setfield (lstate ,-2 ,"NIL" ); 751 752// vim._empty_dict_mt 753lua_createtable (lstate ,0 ,0 ); 754lua_pushcfunction (lstate ,& nlua_empty_dict_tostring ); 755lua_setfield (lstate ,-2 ,"__tostring" ); 756ref_state -> empty_dict_ref = nlua_ref (lstate ,ref_state ,-1 ); 757lua_pushvalue (lstate ,-1 ); 758lua_setfield (lstate ,LUA_REGISTRYINDEX ,"mpack.empty_dict" ); 759lua_setfield (lstate ,-2 ,"_empty_dict_mt" ); 760 761// vim.uv 762if (is_thread ) { 763luv_set_callback (lstate ,nlua_luv_thread_cb_cfpcall ); 764luv_set_thread (lstate ,nlua_luv_thread_cfpcall ); 765luv_set_cthread (lstate ,nlua_luv_thread_cfcpcall ); 766 }else { 767luv_set_loop (lstate ,& main_loop .uv ); 768luv_set_callback (lstate ,nlua_fast_cfpcall ); 769 } 770luaopen_luv (lstate ); 771lua_pushvalue (lstate ,-1 ); 772lua_setfield (lstate ,-3 ,"uv" ); 773 774lua_pushvalue (lstate ,-1 ); 775lua_setfield (lstate ,-3 ,"loop" );// deprecated 776 777// package.loaded.luv = vim.uv 778// otherwise luv will be reinitialized when require'luv' 779lua_getglobal (lstate ,"package" ); 780lua_getfield (lstate ,-1 ,"loaded" ); 781lua_pushvalue (lstate ,-3 ); 782lua_setfield (lstate ,-2 ,"luv" ); 783lua_pop (lstate ,3 ); 784} 785 786static int nlua_module_preloader (lua_State * lstate ) 787{ 788size_t i = (size_t )lua_tointeger (lstate ,lua_upvalueindex (1 )); 789ModuleDef def = builtin_modules [i ]; 790if (luaL_loadbuffer (lstate , (const char * )def .data ,def .size - 1 ,NULL )) { 791return lua_error (lstate ); 792 } 793 794lua_call (lstate ,0 ,1 );// propagates error to caller 795return 1 ; 796} 797 798static bool nlua_init_packages (lua_State * lstate ) 799FUNC_ATTR_NONNULL_ALL 800{ 801// put builtin packages in preload 802lua_getglobal (lstate ,"package" );// [package] 803lua_getfield (lstate ,-1 ,"preload" );// [package, preload] 804for (size_t i = 0 ;i < ARRAY_SIZE (builtin_modules );i ++ ) { 805ModuleDef def = builtin_modules [i ]; 806lua_pushinteger (lstate , (lua_Integer )i );// [package, preload, i] 807lua_pushcclosure (lstate ,nlua_module_preloader ,1 );// [package, preload, cclosure] 808lua_setfield (lstate ,-2 ,def .name );// [package, preload] 809 810if (nlua_disable_preload && strequal (def .name ,"vim.inspect" )) { 811break ; 812 } 813 } 814 815lua_pop (lstate ,2 );// [] 816 817lua_getglobal (lstate ,"require" ); 818lua_pushstring (lstate ,"vim._init_packages" ); 819if (nlua_pcall (lstate ,1 ,0 )) { 820fprintf (stderr ,"%s\n" ,lua_tostring (lstate ,-1 )); 821return false; 822 } 823 824return true; 825} 826 827/// "vim.ui_attach(ns_id, {ext_foo=true}, cb)" function 828static int nlua_ui_attach (lua_State * lstate ) 829FUNC_ATTR_NONNULL_ALL 830{ 831uint32_t ns_id = (uint32_t )luaL_checkinteger (lstate ,1 ); 832 833if (!ns_initialized (ns_id )) { 834return luaL_error (lstate ,"invalid ns_id" ); 835 } 836if (!lua_istable (lstate ,2 )) { 837return luaL_error (lstate ,"opts must be a table" ); 838 } 839if (!lua_isfunction (lstate ,3 )) { 840return luaL_error (lstate ,"callback must be a Lua function" ); 841 } 842 843bool ext_widgets [kUIGlobalCount ]= { false }; 844bool tbl_has_true_val = false; 845 846lua_pushvalue (lstate ,2 ); 847lua_pushnil (lstate ); 848while (lua_next (lstate ,-2 )) { 849// [dict, key, val] 850size_t len ; 851const char * s = lua_tolstring (lstate ,-2 ,& len ); 852bool val = lua_toboolean (lstate ,-1 ); 853 854if (strequal (s ,"set_cmdheight" )) { 855ui_refresh_cmdheight = val ; 856 gotook ; 857 }else { 858for (size_t i = 0 ;i < kUIGlobalCount ;i ++ ) { 859if (strequal (s ,ui_ext_names [i ])) { 860if (val ) { 861tbl_has_true_val = true; 862 } 863ext_widgets [i ]= val ; 864 gotook ; 865 } 866 } 867 } 868 869return luaL_error (lstate ,"Unexpected key: %s" ,s ); 870ok : 871lua_pop (lstate ,1 ); 872 } 873 874if (!tbl_has_true_val ) { 875return luaL_error (lstate ,"opts table must contain at least one 'true' ext_widget" ); 876 } 877 878LuaRef ui_event_cb = nlua_ref_global (lstate ,3 ); 879ui_add_cb (ns_id ,ui_event_cb ,ext_widgets ); 880ui_refresh_cmdheight = true; 881return 0 ; 882} 883 884/// "vim.ui_detach(ns_id)" function 885static int nlua_ui_detach (lua_State * lstate ) 886FUNC_ATTR_NONNULL_ALL 887{ 888uint32_t ns_id = (uint32_t )luaL_checkinteger (lstate ,1 ); 889 890if (!ns_initialized (ns_id )) { 891return luaL_error (lstate ,"invalid ns_id" ); 892 } 893 894ui_remove_cb (ns_id , false); 895return 0 ; 896} 897 898/// Initialize lua interpreter state 899/// 900/// Called by lua interpreter itself to initialize state. 901static bool nlua_state_init (lua_State * const lstate )FUNC_ATTR_NONNULL_ALL 902{ 903lua_pushcfunction (lstate ,& nlua_print ); 905lua_setglobal (lstate ,"print" ); 906 907// debug.debug 908lua_getglobal (lstate ,"debug" ); 909lua_pushcfunction (lstate ,& nlua_debug ); 910lua_setfield (lstate ,-2 ,"debug" ); 911lua_pop (lstate ,1 ); 912 913#ifdef MSWIN 914// os.getenv 915lua_getglobal (lstate ,"os" ); 916lua_pushcfunction (lstate ,& nlua_getenv ); 917lua_setfield (lstate ,-2 ,"getenv" ); 918lua_pop (lstate ,1 ); 919#endif 920 921// os.exit() 922lua_getglobal (lstate ,"os" ); 923lua_pushcfunction (lstate ,& nlua_os_exit ); 924lua_setfield (lstate ,-2 ,"exit" ); 925lua_pop (lstate ,1 ); 926 927// vim 928lua_newtable (lstate ); 929 930// vim.api 931nlua_add_api_functions (lstate ); 932 933// vim.types, vim.type_idx, vim.val_idx 934nlua_init_types (lstate ); 935 936// schedule 937lua_pushcfunction (lstate ,& nlua_schedule ); 938lua_setfield (lstate ,-2 ,"schedule" ); 939 940// in_fast_event 941lua_pushcfunction (lstate ,& nlua_in_fast_event ); 942lua_setfield (lstate ,-2 ,"in_fast_event" ); 943 944// call 945lua_pushcfunction (lstate ,& nlua_call ); 946lua_setfield (lstate ,-2 ,"call" ); 947 948// rpcrequest 949lua_pushcfunction (lstate ,& nlua_rpcrequest ); 950lua_setfield (lstate ,-2 ,"rpcrequest" ); 951 952// rpcnotify 953lua_pushcfunction (lstate ,& nlua_rpcnotify ); 954lua_setfield (lstate ,-2 ,"rpcnotify" ); 955 956// ui_attach 957lua_pushcfunction (lstate ,& nlua_ui_attach ); 958lua_setfield (lstate ,-2 ,"ui_attach" ); 959 960// ui_detach 961lua_pushcfunction (lstate ,& nlua_ui_detach ); 962lua_setfield (lstate ,-2 ,"ui_detach" ); 963 964nlua_common_vim_init (lstate , false); 965 966// Bindings for `vim.wait()`. 967lua_getfield (lstate ,-1 ,"_core" ); 968lua_pushcfunction (lstate ,& nlua_loop_poll ); 969lua_setfield (lstate ,-2 ,"loop_poll" ); 970lua_pushcfunction (lstate ,& nlua_ui_flush ); 971lua_setfield (lstate ,-2 ,"ui_flush" ); 972lua_pushcfunction (lstate ,& nlua_check_interrupt ); 973lua_setfield (lstate ,-2 ,"check_interrupt" ); 974 975// Misc vim._core bindings. 976lua_pushcfunction (lstate ,& nlua_ex_docmd ); 977lua_setfield (lstate ,-2 ,"ex_docmd" ); 978lua_pop (lstate ,1 ); 979 980// patch require() (only for --startuptime) 981if (time_fd != NULL ) { 982lua_getglobal (lstate ,"require" ); 983// Must do this after nlua_common_vim_init where nlua_global_refs is initialized. 984require_ref = nlua_ref_global (lstate ,-1 ); 985lua_pop (lstate ,1 ); 986lua_pushcfunction (lstate ,& nlua_require ); 987lua_setglobal (lstate ,"require" ); 988 } 989 990// internal vim._treesitter... API 991nlua_treesitter_init (lstate ); 992 993nlua_state_add_stdlib (lstate , false); 994 995lua_setglobal (lstate ,"vim" ); 996 997if (!nlua_init_packages (lstate )) { 998return false; 999 } 1000 1001return true; 1002} 1003 1004/// Initializes global Lua interpreter, or exits Nvim on failure. 1005void nlua_init (char ** argv ,int argc ,int lua_arg0 ) 1006{ 1007#ifdef NLUA_TRACK_REFS 1008if (os_env_exists ("NVIM_LUA_NOTRACK" , true)) { 1009nlua_track_refs = true; 1010 } 1011#endif 1012 1013lua_State * lstate = luaL_newstate (); 1014if (lstate == NULL ) { 1015fprintf (stderr ,_ ("E970: Failed to initialize Lua interpreter\n" )); 1016os_exit (1 ); 1017 } 1018luaL_openlibs (lstate ); 1019if (!nlua_state_init (lstate )) { 1020fprintf (stderr ,_ ("E970: Failed to initialize builtin Lua modules\n" )); 1021#ifdef EXITFREE 1022nlua_common_free_all_mem (lstate ); 1023#endif 1024os_exit (1 ); 1025 } 1026 1027luv_set_thread_cb (nlua_thread_acquire_vm ,nlua_common_free_all_mem ); 1028global_lstate = lstate ; 1029active_lstate = lstate ; 1030main_thread = uv_thread_self (); 1031nlua_init_argv (lstate ,argv ,argc ,lua_arg0 ); 1032} 1033 1034static lua_State * nlua_thread_acquire_vm (void ) 1035{ 1036return nlua_init_state (true); 1037} 1038 1039static lua_State * nlua_init_state (bool thread ) 1040{ 1041// If it is called from the main thread, it will attempt to rebuild the cache. 1042const uv_thread_t self = uv_thread_self (); 1043if (uv_thread_equal (& main_thread ,& self )) { 1044runtime_search_path_validate (); 1045 } 1046 1047lua_State * lstate = luaL_newstate (); 1048 1049// Add in the lua standard libraries 1050luaL_openlibs (lstate ); 1051 1052lua_pushcfunction (lstate ,& nlua_print ); 1054lua_setglobal (lstate ,"print" ); 1055 1056lua_pushinteger (lstate ,0 ); 1057lua_setfield (lstate ,LUA_REGISTRYINDEX ,"nlua.refcount" ); 1058 1059// vim 1060lua_newtable (lstate ); 1061 1062nlua_common_vim_init (lstate ,thread ); 1063 1064nlua_state_add_stdlib (lstate , true); 1065 1066lua_createtable (lstate ,0 ,0 ); 1067lua_pushcfunction (lstate ,nlua_thr_api_nvim__get_runtime ); 1068lua_setfield (lstate ,-2 ,"nvim__get_runtime" ); 1069lua_setfield (lstate ,-2 ,"api" ); 1070 1071lua_setglobal (lstate ,"vim" ); 1072 1073nlua_init_packages (lstate ); 1074 1075lua_getglobal (lstate ,"package" ); 1076lua_getfield (lstate ,-1 ,"loaded" ); 1077lua_getglobal (lstate ,"vim" ); 1078lua_setfield (lstate ,-2 ,"vim" ); 1079lua_pop (lstate ,2 ); 1080 1081return lstate ; 1082} 1083 1084/// Disposes global Lua state. Idempotent, harmless if called multiple times. 1085void nlua_free_all_mem (void ) 1086{ 1087if (!global_lstate ) { 1088return ; 1089 } 1090lua_State * lstate = global_lstate ; 1091global_lstate = NULL ; 1092nlua_unref_global (lstate ,require_ref ); 1093nlua_common_free_all_mem (lstate ); 1094nlua_treesitter_free (); 1095} 1096 1097static void nlua_common_free_all_mem (lua_State * lstate ) 1098FUNC_ATTR_NONNULL_ALL 1099{ 1100nlua_ref_state_t * ref_state = nlua_get_ref_state (lstate ); 1101nlua_unref (lstate ,ref_state ,ref_state -> nil_ref ); 1102nlua_unref (lstate ,ref_state ,ref_state -> empty_dict_ref ); 1103 1104#ifdef NLUA_TRACK_REFS 1105if (ref_state -> ref_count ) { 1106fprintf (stderr ,"%d lua references were leaked!" ,ref_state -> ref_count ); 1107 } 1108 1109if (nlua_track_refs ) { 1110// in case there are leaked luarefs, leak the associated memory 1111// to get LeakSanitizer stacktraces on exit 1112map_destroy (int ,& ref_state -> ref_markers ); 1113 } 1114#endif 1115 1116lua_close (lstate ); 1117} 1118 1119static void nlua_print_event (void ** argv ) 1120{ 1121msg_ext_no_fast (); 1122if (msg_use_printf ()&& on_print .type == kCallbackNone ) { 1123msg_start ();// flush incomplete message 1124printf ("%.*s\n" , (int )(intptr_t )argv [1 ]- 1 , (char * )argv [0 ]); 1125xfree (argv [0 ]); 1126 }else { 1127HlMessage msg = KV_INITIAL_VALUE ; 1128HlMessageChunk chunk = { { .data = argv [0 ], .size = (size_t )(intptr_t )argv [1 ]- 1 },0 }; 1129kv_push (msg ,chunk ); 1130bool needs_clear = false; 1131msg_multihl (NIL ,msg ,"lua_print" , true, false,NULL ,& needs_clear ); 1132 } 1133} 1134 1135/// Implements Lua print() as a Nvim message. 1136/// 1137/// @param lstate Lua interpreter state. 1138static int nlua_print (lua_State * const lstate ) 1139FUNC_ATTR_NONNULL_ALL 1140{ 1141const int nargs = lua_gettop (lstate ); 1142lua_getglobal (lstate ,"tostring" ); 1143const char * errmsg = NULL ; 1144size_t errmsg_len = 0 ; 1145garray_T msg_ga ; 1146ga_init (& msg_ga ,1 ,80 ); 1147int curargidx = 1 ; 1148for (;curargidx <=nargs ;curargidx ++ ) { 1149lua_pushvalue (lstate ,-1 );// tostring 1150lua_pushvalue (lstate ,curargidx );// arg 1151// Do not use nlua_pcall here to avoid duplicate stack trace information 1152if (lua_pcall (lstate ,1 ,1 ,0 )|| lua_type (lstate ,-1 )!= LUA_TSTRING ) { 1153// NB: this might try tostring once more to print a weird error from 1154// a __tostring methamethod but we stop after that. 1155errmsg = nlua_get_error (lstate ,& errmsg_len ); 1156 gotonlua_print_error ; 1157 } 1158 1159size_t len ; 1160const char * const s = lua_tolstring (lstate ,-1 ,& len ); 1161ga_concat_len (& msg_ga ,s ,len ); 1162if (curargidx < nargs ) { 1163ga_append (& msg_ga ,' ' ); 1164 } 1165lua_pop (lstate ,1 ); 1166 } 1167ga_append (& msg_ga ,NUL ); 1168 1169lua_getfield (lstate ,LUA_REGISTRYINDEX ,"nvim.thread" ); 1170bool is_thread = lua_toboolean (lstate ,-1 ); 1171lua_pop (lstate ,1 ); 1172 1173if (is_thread ) { 1174loop_schedule_deferred (& main_loop , 1175event_create (nlua_print_event , 1176msg_ga .ga_data , 1177 (void * )(intptr_t )msg_ga .ga_len )); 1178 }else if (in_fast_callback ) { 1179multiqueue_put (main_loop .events ,nlua_print_event , 1180msg_ga .ga_data , (void * )(intptr_t )msg_ga .ga_len ); 1181 }else { 1182nlua_print_event ((void * []){msg_ga .ga_data , (void * )(intptr_t )msg_ga .ga_len }); 1183 } 1184return 0 ; 1185 1186nlua_print_error : 1187ga_clear (& msg_ga ); 1188char * buff = xmalloc (IOSIZE ); 1189const char * fmt = _ ("E5114: Converting print argument #%i: %.*s" ); 1190size_t len = (size_t )vim_snprintf (buff ,IOSIZE ,fmt ,curargidx , 1191 (int )errmsg_len ,errmsg ); 1192lua_pushlstring (lstate ,buff ,len ); 1193xfree (buff ); 1194return lua_error (lstate ); 1195} 1196 1197/// require() for --startuptime 1198/// 1199/// @param lstate Lua interpreter state. 1200static int nlua_require (lua_State * const lstate ) 1201FUNC_ATTR_NONNULL_ALL 1202{ 1203const char * name = luaL_checkstring (lstate ,1 ); 1204lua_settop (lstate ,1 ); 1205// [ name ] 1206 1207// try cached module from package.loaded first 1208lua_getfield (lstate ,LUA_REGISTRYINDEX ,"_LOADED" ); 1209lua_getfield (lstate ,2 ,name ); 1210// [ name package.loaded module ] 1211if (lua_toboolean (lstate ,-1 )) { 1212return 1 ; 1213 } 1214lua_pop (lstate ,2 ); 1215// [ name ] 1216 1217// push original require below the module name 1218nlua_pushref (lstate ,require_ref ); 1219lua_insert (lstate ,1 ); 1220// [ require name ] 1221 1222if (time_fd == NULL ) { 1223// after log file was closed, try to restore 1224// global require to the original function... 1225lua_getglobal (lstate ,"require" ); 1226// ...only if it's still referencing this wrapper, 1227// to not overwrite it in case someone happened to 1228// patch it in the meantime... 1229if (lua_iscfunction (lstate ,-1 )&& lua_tocfunction (lstate ,-1 )== nlua_require ) { 1230lua_pushvalue (lstate ,1 ); 1231lua_setglobal (lstate ,"require" ); 1232 } 1233lua_pop (lstate ,1 ); 1234 1235// ...and then call require directly. 1236lua_call (lstate ,1 ,1 ); 1237return 1 ; 1238 } 1239 1240proftime_T rel_time ; 1241proftime_T start_time ; 1242time_push (& rel_time ,& start_time ); 1243int status = lua_pcall (lstate ,1 ,1 ,0 ); 1244if (status == 0 ) { 1245vim_snprintf (IObuff ,IOSIZE ,"require('%s')" ,name ); 1246time_msg (IObuff ,& start_time ); 1247 } 1248time_pop (rel_time ); 1249 1250return status == 0 ?1 :lua_error (lstate ); 1251} 1252 1253/// debug.debug: interaction with user while debugging. 1254/// 1255/// @param lstate Lua interpreter state. 1256static int nlua_debug (lua_State * lstate ) 1257FUNC_ATTR_NONNULL_ALL 1258{ 1259const typval_T input_args []= { 1260 { 1261 .v_lock = VAR_FIXED , 1262 .v_type = VAR_STRING , 1263 .vval .v_string = "lua_debug> " , 1264 }, 1265 { 1266 .v_type = VAR_UNKNOWN , 1267 }, 1268 }; 1269while (true) { 1270lua_settop (lstate ,0 ); 1271typval_T input ; 1272get_user_input (input_args ,& input , false, false); 1273 1274if (ui_has (kUICmdline )) { 1275snprintf (IObuff ,IOSIZE ,"lua_debug> %s" ,input .vval .v_string ); 1276ui_ext_cmdline_block_append (0 ,IObuff ); 1277 }else { 1278msg_putchar ('\n' );// Avoid outputting on input line. 1279 } 1280 1281if (input .v_type != VAR_STRING 1282|| input .vval .v_string == NULL 1283|| * input .vval .v_string == NUL 1284|| strcmp (input .vval .v_string ,"cont" )== 0 ) { 1285tv_clear (& input ); 1286if (ui_has (kUICmdline )) { 1287ui_ext_cmdline_block_leave (); 1288 } 1289return 0 ; 1290 } 1291 1292if (luaL_loadbuffer (lstate ,input .vval .v_string , 1293strlen (input .vval .v_string ),"=(debug command)" )) { 1294nlua_error (lstate ,_ ("E5115: Loading Lua debug string: %.*s" )); 1295 }else if (nlua_pcall (lstate ,0 ,0 )) { 1296nlua_error (lstate ,_ ("E5116: Calling Lua debug string: %.*s" )); 1297 } 1298tv_clear (& input ); 1299 } 1300return 0 ; 1301} 1302 1303/// "vim.in_fast_event()" function. 1304int nlua_in_fast_event (lua_State * lstate ) 1305{ 1306lua_pushboolean (lstate ,in_fast_callback > 0 ); 1307return 1 ; 1308} 1309 1310static bool viml_func_is_fast (const char * name ) 1311{ 1312const EvalFuncDef * const fdef = find_internal_func (name ); 1313if (fdef ) { 1314return fdef -> fast ; 1315 } 1316// Not a Vimscript function 1317return false; 1318} 1319 1320/// "vim.call()", aka "vim.fn". 1321int nlua_call (lua_State * lstate ) 1322{ 1323Error err = ERROR_INIT ; 1324size_t name_len ; 1325const char * name = luaL_checklstring (lstate ,1 ,& name_len ); 1326if (!nlua_is_deferred_safe ()&& !viml_func_is_fast (name )) { 1327size_t length = MIN (strlen (name ),100 )+ sizeof ("Vimscript function \"\"" ); 1328vim_snprintf (IObuff ,length ,"Vimscript function \"%s\"" ,name ); 1329int ret = luaL_error (lstate ,e_fast_api_disabled ,IObuff ); 1330return ret ; 1331 } 1332 1333int nargs = lua_gettop (lstate )- 1 ; 1334if (nargs > MAX_FUNC_ARGS ) { 1335return luaL_error (lstate ,"Function called with too many arguments" ); 1336 } 1337 1338// Fast path: if the vimfn is defined with `func_lua`, call the Lua function 1339// directly without Lua→typval→Object→Lua round-trip. 1340const char * func_lua = find_internal_func_lua (name ); 1341if (func_lua ) { 1342lua_getglobal (lstate ,"require" ); 1343lua_pushliteral (lstate ,"vim._core.vimfn" ); 1344if (lua_pcall (lstate ,1 ,1 ,0 )!= 0 ) { 1345return lua_error (lstate ); 1346 } 1347lua_getfield (lstate ,-1 ,func_lua ); 1348lua_remove (lstate ,-2 );// remove module table 1349// Push args (still on the stack as Lua values). 1350for (int j = 0 ;j < nargs ;j ++ ) { 1351lua_pushvalue (lstate ,j + 2 ); 1352 } 1353if (lua_pcall (lstate ,nargs ,1 ,0 )!= 0 ) { 1354return lua_error (lstate ); 1355 } 1356return 1 ; 1357 } 1358 1359typval_T vim_args [MAX_FUNC_ARGS + 1 ]; 1360int i = 0 ;// also used for freeing the variables 1361for (;i < nargs ;i ++ ) { 1362lua_pushvalue (lstate ,i + 2 ); 1363if (!nlua_pop_typval (lstate ,& vim_args [i ])) { 1364api_set_error (& err ,kErrorTypeException , 1365"error converting argument %d" ,i + 1 ); 1366 gotofree_vim_args ; 1367 } 1368 } 1369 1370// TODO(bfredl): this should be simplified in error handling refactor 1371force_abort = false; 1372suppress_errthrow = false; 1373did_throw = false; 1374did_emsg = false; 1375 1376typval_T rettv ; 1377funcexe_T funcexe = FUNCEXE_INIT ; 1378funcexe .fe_firstline = curwin -> w_cursor .lnum ; 1379funcexe .fe_lastline = curwin -> w_cursor .lnum ; 1380funcexe .fe_evaluate = true; 1381const sctx_T save_current_sctx = api_set_sctx (LUA_INTERNAL_CALL ); 1382 1383TRY_WRAP (& err , { 1384// call_func() retval is deceptive, ignore it. Instead we set `msg_list` 1385// (TRY_WRAP) to capture abort-causing non-exception errors. 1386 (void )call_func (name , (int )name_len ,& rettv ,nargs ,vim_args ,& funcexe ); 1387 }); 1388current_sctx = save_current_sctx ; 1389 1390if (!ERROR_SET (& err )) { 1391nlua_push_typval (lstate ,& rettv ,0 ); 1392 } 1393tv_clear (& rettv ); 1394 1395free_vim_args : 1396while (i > 0 ) { 1397tv_clear (& vim_args [-- i ]); 1398 } 1399if (ERROR_SET (& err )) { 1400lua_pushstring (lstate ,err .msg ); 1401api_clear_error (& err ); 1402return lua_error (lstate ); 1403 } 1404return 1 ; 1405} 1406 1407static int nlua_rpcrequest (lua_State * lstate ) 1408{ 1409if (!nlua_is_deferred_safe ()) { 1410return luaL_error (lstate ,e_fast_api_disabled ,"rpcrequest" ); 1411 } 1412return nlua_rpc (lstate , true); 1413} 1414 1415static int nlua_rpcnotify (lua_State * lstate ) 1416{ 1417return nlua_rpc (lstate , false); 1418} 1419 1420static int nlua_rpc (lua_State * lstate ,bool request ) 1421{ 1422size_t name_len ; 1423uint64_t chan_id = (uint64_t )luaL_checkinteger (lstate ,1 ); 1424const char * name = luaL_checklstring (lstate ,2 ,& name_len ); 1425int nargs = lua_gettop (lstate )- 2 ; 1426Error err = ERROR_INIT ; 1427Arena arena = ARENA_EMPTY ; 1428 1429Array args = arena_array (& arena , (size_t )nargs ); 1430for (int i = 0 ;i < nargs ;i ++ ) { 1431lua_pushvalue (lstate ,i + 3 ); 1432ADD (args ,nlua_pop_Object (lstate , false,& arena ,& err )); 1433if (ERROR_SET (& err )) { 1434 gotocheck_err ; 1435 } 1436 } 1437 1438if (request ) { 1439ArenaMem res_mem = NULL ; 1440Object result = rpc_send_call (chan_id ,name ,args ,& res_mem ,& err ); 1441if (!ERROR_SET (& err )) { 1442nlua_push_Object (lstate ,& result ,0 ); 1443arena_mem_free (res_mem ); 1444 } 1445 }else { 1446if (!rpc_send_event (chan_id ,name ,args )) { 1447api_set_error (& err ,kErrorTypeValidation , 1448"Invalid channel: %" PRIu64 ,chan_id ); 1449 } 1450 } 1451 1452check_err : 1453arena_mem_free (arena_finish (& arena )); 1454 1455if (ERROR_SET (& err )) { 1456lua_pushstring (lstate ,err .msg ); 1457api_clear_error (& err ); 1458return lua_error (lstate ); 1459 } 1460 1461return request ?1 :0 ; 1462} 1463 1464static int nlua_nil_tostring (lua_State * lstate ) 1465{ 1466lua_pushstring (lstate ,"vim.NIL" ); 1467return 1 ; 1468} 1469 1470static int nlua_nil_index (lua_State * lstate ) 1471{ 1472return luaL_error (lstate ,"attempt to index vim.NIL" ); 1473} 1474 1475static int nlua_empty_dict_tostring (lua_State * lstate ) 1476{ 1477lua_pushstring (lstate ,"vim.empty_dict()" ); 1478return 1 ; 1479} 1480 1481#ifdef MSWIN 1482/// os.getenv: override os.getenv to maintain coherency. #9681 1483/// 1484/// uv_os_setenv uses SetEnvironmentVariableW which does not update _environ. 1485/// 1486/// @param lstate Lua interpreter state. 1487static int nlua_getenv (lua_State * lstate ) 1488{ 1489lua_pushstring (lstate ,os_getenv_noalloc (luaL_checkstring (lstate ,1 ))); 1490return 1 ; 1491} 1492#endif 1493 1494/// add the value to the registry 1495/// The current implementation does not support calls from threads. 1496LuaRef nlua_ref (lua_State * lstate ,nlua_ref_state_t * ref_state ,int index ) 1497{ 1498lua_pushvalue (lstate ,index ); 1499LuaRef ref = luaL_ref (lstate ,LUA_REGISTRYINDEX ); 1500if (ref > 0 ) { 1501ref_state -> ref_count ++ ; 1502#ifdef NLUA_TRACK_REFS 1503if (nlua_track_refs ) { 1504// dummy allocation to make LeakSanitizer track our luarefs 1505pmap_put (int )(& ref_state -> ref_markers ,ref ,xmalloc (3 )); 1506 } 1507#endif 1508 } 1509return ref ; 1510} 1511 1512// TODO(lewis6991): Currently cannot be run in __gc metamethods as they are 1513// invoked in lua_close() which can be invoked after the ref_markers map is 1514// destroyed in nlua_common_free_all_mem. 1515LuaRef nlua_ref_global (lua_State * lstate ,int index ) 1516{ 1517return nlua_ref (lstate ,nlua_global_refs ,index ); 1518} 1519 1520/// remove the value from the registry 1521void nlua_unref (lua_State * lstate ,nlua_ref_state_t * ref_state ,LuaRef ref ) 1522{ 1523if (ref > 0 ) { 1524ref_state -> ref_count -- ; 1525#ifdef NLUA_TRACK_REFS 1526// NB: don't remove entry from map to track double-unref 1527if (nlua_track_refs ) { 1528xfree (pmap_get (int )(& ref_state -> ref_markers ,ref )); 1529 } 1530#endif 1531luaL_unref (lstate ,LUA_REGISTRYINDEX ,ref ); 1532 } 1533} 1534 1535void nlua_unref_global (lua_State * lstate ,LuaRef ref ) 1536{ 1537nlua_unref (lstate ,nlua_global_refs ,ref ); 1538} 1539 1540void api_free_luaref (LuaRef ref ) 1541{ 1542nlua_unref_global (global_lstate ,ref ); 1543} 1544 1545/// push a value referenced in the registry 1546void nlua_pushref (lua_State * lstate ,LuaRef ref ) 1547{ 1548lua_rawgeti (lstate ,LUA_REGISTRYINDEX ,ref ); 1549} 1550 1551/// Gets a new reference to an object stored at original_ref 1552/// 1553/// NOTE: It does not copy the value, it creates a new ref to the lua object. 1554/// Leaves the stack unchanged. 1555LuaRef api_new_luaref (LuaRef original_ref ) 1556{ 1557if (original_ref == LUA_NOREF ) { 1558return LUA_NOREF ; 1559 } 1560 1561lua_State * const lstate = global_lstate ; 1562nlua_pushref (lstate ,original_ref ); 1563LuaRef new_ref = nlua_ref_global (lstate ,-1 ); 1564lua_pop (lstate ,1 ); 1565return new_ref ; 1566} 1567 1568/// Formats `fmt` (must contain a single "%.*s" for `bodylen`-byte `body`) into a Lua chunk and runs 1569/// it via nlua_exec_typval(). 1570static void nlua_exec_typval_fmt (const char * fmt ,const char * body ,size_t bodylen , 1571const char * name ,typval_T * args ,int argcount ,bool special , 1572typval_T * ret_tv ) 1573FUNC_ATTR_PRINTF (1 ,0 ) 1574{ 1575// Don't use shared IObuff; may reenter Lua (e.g. 'statusline' eval during a redraw). #40616 1576// This local buf is safe across (re)entrant calls since luaL_loadbuffer() copies before exec. 1577static char lcmd_buf [IOSIZE ]; 1578char * lcmd = lcmd_buf ; 1579int lcmd_len = vim_snprintf (lcmd_buf ,sizeof (lcmd_buf ),fmt , (int )bodylen ,body ); 1580if (lcmd_len >=IOSIZE ) { 1581lcmd = xmalloc ((size_t )lcmd_len + 1 ); 1582vim_snprintf (lcmd , (size_t )lcmd_len + 1 ,fmt , (int )bodylen ,body ); 1583 } 1584 1585nlua_exec_typval (lcmd , (size_t )lcmd_len ,name ,args ,argcount ,special ,ret_tv ); 1586 1587if (lcmd != lcmd_buf ) { 1588xfree (lcmd ); 1589 } 1590} 1591 1592/// Implements vimfn: luaeval(). 1593void nlua_call_luaeval (const String str ,typval_T * const arg ,typval_T * const ret_tv ) 1594FUNC_ATTR_NONNULL_ALL 1595{ 1596nlua_exec_typval_fmt ("local _A=select(1,...) return (%.*s)" ,str .data ,str .size ,"luaeval()" ,arg , 15971 , true,ret_tv ); 1598} 1599 1600/// Calls v:lua.func() with typval args. 1601void nlua_call_vlua (const char * str ,size_t len ,typval_T * const args ,int argcount , 1602typval_T * ret_tv ) 1603FUNC_ATTR_NONNULL_ALL 1604{ 1605nlua_exec_typval_fmt ("return %.*s(...)" ,str ,len ,"v:lua" ,args ,argcount , false,ret_tv ); 1606} 1607 1608/// Calls a Lua completion function (stored as LuaRef) for cmdline expansion. 1609void nlua_call_user_expand_func (expand_T * xp ,typval_T * ret_tv ) 1610FUNC_ATTR_NONNULL_ALL 1611{ 1612lua_State * const lstate = global_lstate ; 1613 1614nlua_pushref (lstate ,xp -> xp_luaref ); 1615lua_pushstring (lstate ,xp -> xp_pattern ); 1616lua_pushstring (lstate ,xp -> xp_line ); 1617lua_pushinteger (lstate ,xp -> xp_col ); 1618 1619if (nlua_pcall (lstate ,3 ,1 )) { 1620nlua_error (lstate ,_ ("E5108: Lua function: %.*s" )); 1621return ; 1622 } 1623 1624nlua_pop_typval (lstate ,ret_tv ); 1625} 1626 1627/// Executes a Lua chunk with typval arguments and optional typval return. 1628static void nlua_exec_typval (const char * lcmd ,size_t lcmd_len ,const char * name , 1629typval_T * const args ,int argcount ,bool special ,typval_T * ret_tv ) 1630{ 1631if (check_secure ()) { 1632if (ret_tv ) { 1633ret_tv -> v_type = VAR_NUMBER ; 1634ret_tv -> vval .v_number = 0 ; 1635 } 1636return ; 1637 } 1638 1639lua_State * const lstate = global_lstate ; 1640 1641// 1. Compile lcmd into a Lua chunk (function), push it on the stack. 1642// 1643// TODO(justinmk): Cache the chunk in LUA_REGISTRYINDEX? But one-off callers (:lua, luaeval) may 1644// bloat the cache. Could add a `cache:boolean` param. 1645if (luaL_loadbuffer (lstate ,lcmd ,lcmd_len ,name )) { 1646nlua_error (lstate ,_ ("E5107: Lua: %.*s" )); 1647return ; 1648 } 1649 1650// 2. Push typval args as Lua values. Stack: [chunk, arg1, ..., argN]. 1651PUSH_ALL_TYPVALS (lstate ,args ,argcount ,special ); 1652 1653// 3. Call: chunk(arg1, ..., argN). Essentially loadstring(). 1654if (nlua_pcall (lstate ,argcount ,ret_tv ?1 :0 )) { 1655nlua_error (lstate ,_ ("E5108: Lua: %.*s" )); 1656return ; 1657 } 1658 1659if (ret_tv ) { 1660nlua_pop_typval (lstate ,ret_tv ); 1661 } 1662} 1663 1664/// Execute Lua code from a growarray of lines. Used by ":lua << EOF". 1665void nlua_exec_ga (garray_T * ga ,char * name ) 1666{ 1667char * code = ga_concat_strings (ga ,"\n" ); 1668size_t len = strlen (code ); 1669nlua_exec_typval (code ,len ,name ,NULL ,0 , false,NULL ); 1670xfree (code ); 1671} 1672 1673/// Calls a Lua callable from Vimscript. 1674/// 1675/// @param[in] lstate Lua State 1676/// @param[in] lua_cb Lua Callable 1677/// @param[in] argcount Count of typval arguments 1678/// @param[in] argvars Typval Arguments 1679/// @param[out] rettv The return value from the called function. 1680int nlua_exec_typval_callable (LuaRef lua_cb ,int argcount ,typval_T * argvars ,typval_T * rettv ) 1681{ 1682lua_State * lstate = global_lstate ; 1683 1684nlua_pushref (lstate ,lua_cb ); 1685 1686PUSH_ALL_TYPVALS (lstate ,argvars ,argcount , false); 1687 1688if (nlua_pcall (lstate ,argcount ,1 )) { 1689nlua_error (lstate ,_ ("Lua callback: %.*s" )); 1690return FCERR_OTHER ; 1691 } 1692 1693nlua_pop_typval (lstate ,rettv ); 1694 1695return FCERR_NONE ; 1696} 1697 1698/// Execute Lua string 1699/// 1700/// Used for nvim_exec_lua() and internally to execute a lua string. 1701/// 1702/// @param[in] str String to execute. 1703/// @param[in] chunkname Chunkname, defaults to "<nvim>". 1704/// @param[in] args array of ... args 1705/// @param[in] mode Whether and how the the return value should be converted to Object 1706/// @param[in] arena can be NULL, then nested allocations are used 1707/// @param[out] err Location where error will be saved. 1708/// 1709/// @return Return value of the execution. 1710Object nlua_exec (const String str ,const char * chunkname ,const Array args ,LuaRetMode mode , 1711Arena * arena ,Error * err ) 1712{ 1713lua_State * const lstate = global_lstate ; 1714 1715int top = lua_gettop (lstate ); 1716const char * name = (chunkname && chunkname [0 ]) ?chunkname :"<nvim>" ; 1717if (luaL_loadbuffer (lstate ,str .data ,str .size ,name )) { 1718size_t len ; 1719const char * errstr = lua_tolstring (lstate ,-1 ,& len ); 1720api_set_error (err ,kErrorTypeValidation ,"Lua: %.*s" , (int )len ,errstr ); 1721return NIL ; 1722 } 1723 1724for (size_t i = 0 ;i < args .size ;i ++ ) { 1725nlua_push_Object (lstate ,& args .items [i ],0 ); 1726 } 1727 1728if (nlua_pcall (lstate , (int )args .size ,1 )) { 1729size_t len ; 1730const char * errstr = lua_tolstring (lstate ,-1 ,& len ); 1731api_set_error (err ,kErrorTypeException ,"Lua: %.*s" , (int )len ,errstr ); 1732return NIL ; 1733 } 1734 1735return nlua_call_pop_retval (lstate ,mode ,arena ,top ,err ); 1736} 1737 1738/// Calls a Lua function with typval args. 1739/// 1740/// Converts argvars directly to Lua values (no Object intermediate), calls the Lua function, and 1741/// converts the result back to typval_T. 1742/// 1743/// @param module Lua module name, e.g. "vim._core.server". 1744/// @param func Function name in the module, e.g. "serverlist". 1745/// @param argvars typval args (VAR_UNKNOWN-terminated). 1746/// @param rettv Return value (caller must tv_clear), or NULL to discard. 1747void nlua_call_typval (const char * module ,const char * func ,typval_T * argvars ,typval_T * rettv ) 1748{ 1749int argcount = 0 ; 1750for (typval_T * tv = argvars ;tv -> v_type != VAR_UNKNOWN ;tv ++ ) { 1751argcount ++ ; 1752 } 1753 1754char buf [256 ]; 1755snprintf (buf ,sizeof (buf ),"return require('%s').%s(...)" ,module ,func ); 1756 1757nlua_exec_typval (buf ,strlen (buf ),module ,argvars ,argcount , false,rettv ); 1758} 1759 1760/// Calls Lua to implement an excmd. Passes `eap` + `cmdmod` to Lua as a dict arg, which is arranged 1761/// to match the Lua type `vim.api.keyset.create_user_command.command_args`. 1762/// 1763/// @param module Lua module name, e.g. "vim._core.ex_cmd". 1764/// @param func Function name in the module, e.g. "ex_log". 1765/// @param eap Excmd info, passed as Lua arg1. 1766/// @param cmod Excmd mods, included in Lua arg1. 1767/// @param extra (Optional) Passed as Lua arg2. 1768/// @return true on success, false on error (message already emitted). 1769bool nlua_call_excmd (const char * module ,const char * func ,exarg_T * eap ,const cmdmod_T * cmod , 1770typval_T * extra ) 1771{ 1772lua_State * const lstate = global_lstate ; 1773 1774lua_getglobal (lstate ,"require" ); 1775lua_pushstring (lstate ,module ); 1776if (lua_pcall (lstate ,1 ,1 ,0 )!= 0 ) { 1777nlua_error (lstate ,"E5108: %s" ); 1778return false; 1779 } 1780lua_getfield (lstate ,-1 ,func ); 1781lua_remove (lstate ,-2 ); 1782 1783lua_newtable (lstate ); 1784nlua_push_eap (lstate ,eap ,cmod ); 1785 1786int nargs = 1 ; 1787if (extra ) { 1788nlua_push_typval (lstate ,extra ,0 ); 1789nargs = 2 ; 1790 } 1791 1792if (nlua_pcall (lstate ,nargs ,0 )) { 1793// Not "E5108" because this is a logical/application error, not a "Lua error". 1794emsg (lua_tostring (lstate ,-1 )); 1795lua_pop (lstate ,1 ); 1796return false; 1797 } 1798return true; 1799} 1800 1801/// Checks if a LuaRef refers to a function. 1802bool nlua_ref_is_function (LuaRef ref ) 1803{ 1804lua_State * const lstate = global_lstate ; 1805nlua_pushref (lstate ,ref ); 1806 1807// TODO(tjdevries): This should probably check for callable tables as well. 1808// We should put some work maybe into simplifying how all of that works 1809bool is_function = (lua_type (lstate ,-1 )== LUA_TFUNCTION ); 1810lua_pop (lstate ,1 ); 1811 1812return is_function ; 1813} 1814 1815/// call a LuaRef as a function (or table with __call metamethod) 1816/// 1817/// @param ref the reference to call (not consumed) 1818/// @param name if non-NULL, sent to callback as first arg 1819/// if NULL, only args are used 1820/// @param mode Whether and how the the return value should be converted to Object 1821/// @param arena can be NULL, then nested allocations are used 1822/// @param err Error details, if any (if NULL, errors are echoed) 1823/// @return Return value of function, as per mode 1824Object nlua_call_ref (LuaRef ref ,const char * name ,Array args ,LuaRetMode mode ,Arena * arena , 1825Error * err ) 1826{ 1827return nlua_call_ref_ctx (false,ref ,name ,args ,mode ,arena ,err ); 1828} 1829 1830static int mode_ret (LuaRetMode mode ) 1831{ 1832return (mode == kRetMulti || mode == kRetMultiStack ) ?LUA_MULTRET :1 ; 1833} 1834 1835/// Like nlua_call_ref, but with an option to run in fast (api-fast) context. 1836Object nlua_call_ref_ctx (bool fast ,LuaRef ref ,const char * name ,Array args ,LuaRetMode mode , 1837Arena * arena ,Error * err ) 1838{ 1839// Use active_lstate (set by ENTER_LUA_ACTIVE_STATE in gen_api_dispatch.lua) so callbacks run on 1840// the caller's Lua thread. This matters for coroutines: with global_lstate, return values pushed 1841// by kRetMultiStack would land on the main thread's stack, instead of coroutine stack. 1842lua_State * const lstate = active_lstate ; 1843int top = lua_gettop (lstate ); 1844nlua_pushref (lstate ,ref ); 1845int nargs = (int )args .size ; 1846if (name != NULL ) { 1847lua_pushstring (lstate ,name ); 1848nargs ++ ; 1849 } 1850for (size_t i = 0 ;i < args .size ;i ++ ) { 1851nlua_push_Object (lstate ,& args .items [i ],0 ); 1852 } 1853 1854if (fast ) { 1855if (nlua_fast_cfpcall (lstate ,nargs ,mode_ret (mode ),-1 )< 0 ) { 1856// error is already scheduled, set anyways to convey failure. 1857api_set_error (err ,kErrorTypeException ,"fast context failure" ); 1858return NIL ; 1859 } 1860 }else if (nlua_pcall (lstate ,nargs ,mode_ret (mode ))) { 1861// if err is passed, the caller will deal with the error. 1862if (err ) { 1863size_t len ; 1864const char * errstr = lua_tolstring (lstate ,-1 ,& len ); 1865api_set_error (err ,kErrorTypeException ,"Lua: %.*s" , (int )len ,errstr ); 1866 }else { 1867nlua_error (lstate ,_ ("Lua callback: %.*s" )); 1868 } 1869return NIL ; 1870 } 1871 1872return nlua_call_pop_retval (lstate ,mode ,arena ,top ,err ); 1873} 1874 1875static Object nlua_call_pop_retval (lua_State * lstate ,LuaRetMode mode ,Arena * arena ,int pretop , 1876Error * err ) 1877{ 1878if (mode != kRetMulti && mode != kRetMultiStack && lua_isnil (lstate ,-1 )) { 1879lua_pop (lstate ,1 ); 1880return NIL ; 1881 } 1882Error dummy = ERROR_INIT ; 1883Error * perr = err ?err :& dummy ; 1884 1885switch (mode ) { 1886case kRetNilBool : { 1887bool bool_value = lua_toboolean (lstate ,-1 ); 1888lua_pop (lstate ,1 ); 1889 1890return BOOLEAN_OBJ (bool_value ); 1891 } 1892case kRetLuaref : { 1893LuaRef ref = nlua_ref_global (lstate ,-1 ); 1894lua_pop (lstate ,1 ); 1895 1896return LUAREF_OBJ (ref ); 1897 } 1898case kRetObject : 1899return nlua_pop_Object (lstate , false,arena ,perr ); 1900case kRetMulti : 1901 ; 1902int nres = lua_gettop (lstate )- pretop ; 1903Array res = arena_array (arena , (size_t )nres ); 1904for (int i = 0 ;i < nres ;i ++ ) { 1905res .items [nres - i - 1 ]= nlua_pop_Object (lstate , false,arena ,perr ); 1906if (ERROR_SET (perr )) { 1907return NIL ; 1908 } 1909 } 1910res .size = (size_t )nres ; 1911return ARRAY_OBJ (res ); 1912case kRetMultiStack : 1913 ; 1914return NIL ; 1915 } 1916UNREACHABLE ; 1917} 1918 1919/// check if the current execution context is safe for calling deferred API 1920/// methods. Luv callbacks are unsafe as they are called inside the uv loop. 1921bool nlua_is_deferred_safe (void ) 1922{ 1923return in_fast_callback == 0 ; 1924} 1925 1926/// Implements `:lua` and `:lua ={expr}`. 1927/// 1928/// @param eap Vimscript `:lua {code}`, `:{range}lua`, or `:lua ={expr}` command. 1929void ex_lua (exarg_T * const eap ) 1930FUNC_ATTR_NONNULL_ALL 1931{ 1932// ":{range}lua", only if no {code} 1933if (* eap -> arg == NUL ) { 1934if (eap -> addr_count > 0 ) { 1935cmd_source_buffer (eap , true); 1936 }else { 1937emsg (_ (e_argreq )); 1938 } 1939return ; 1940 } 1941 1942size_t len ; 1943char * code = script_get (eap ,& len ); 1944if (eap -> skip || code == NULL ) { 1945xfree (code ); 1946return ; 1947 } 1948 1949// ":lua {code}", ":={expr}" or ":lua ={expr}" 1950// 1951// When "=expr" is used transform it to "vim._print(true, expr)". 1952if (eap -> cmdidx == CMD_equal || code [0 ]== '=' ) { 1953size_t off = (eap -> cmdidx == CMD_equal ) ?0 :1 ; 1954len += sizeof ("vim._print(true, )" )- 1 - off ; 1955// `nlua_exec_typval` doesn't expect NUL-terminated string so `len` must end before NUL byte. 1956char * code_buf = xmallocz (len ); 1957vim_snprintf (code_buf ,len + 1 ,"vim._print(true, %s)" ,code + off ); 1958xfree (code ); 1959code = code_buf ; 1960 } 1961 1962nlua_exec_typval (code ,len ,":lua" ,NULL ,0 , false,NULL ); 1963 1964xfree (code ); 1965} 1966 1967/// Implements `:luado`: executes Lua code for-each line in a buffer range. 1968/// 1969/// @param eap Vimscript `:luado {code}` command. 1970void ex_luado (exarg_T * const eap ) 1971FUNC_ATTR_NONNULL_ALL 1972{ 1973if (u_save (eap -> line1 - 1 ,eap -> line2 + 1 )== FAIL ) { 1974emsg (_ ("cannot save undo information" )); 1975return ; 1976 } 1977const char * const cmd = eap -> arg ; 1978const size_t cmd_len = strlen (cmd ); 1979 1980lua_State * const lstate = global_lstate ; 1981 1982#define DOSTART "return function(line, linenr) " 1983#define DOEND " end" 1984const size_t lcmd_len = (cmd_len 1985+ (sizeof (DOSTART )- 1 ) 1986+ (sizeof (DOEND )- 1 )); 1987// Don't use shared IObuff; may reenter Lua (e.g. 'statusline' eval during a redraw). #40616 1988// This local buf is safe across (re)entrant calls since luaL_loadbuffer() copies before exec. 1989static char lcmd_buf [IOSIZE ]; 1990char * lcmd ; 1991if (lcmd_len < IOSIZE ) { 1992lcmd = lcmd_buf ; 1993 }else { 1994lcmd = xmalloc (lcmd_len + 1 ); 1995 } 1996memcpy (lcmd ,DOSTART ,sizeof (DOSTART )- 1 ); 1997memcpy (lcmd + sizeof (DOSTART )- 1 ,cmd ,cmd_len ); 1998memcpy (lcmd + sizeof (DOSTART )- 1 + cmd_len ,DOEND ,sizeof (DOEND )- 1 ); 1999#undef DOSTART 2000#undef DOEND 2001 2002if (luaL_loadbuffer (lstate ,lcmd ,lcmd_len ,":luado" )) { 2003nlua_error (lstate ,_ ("E5109: Lua: %.*s" )); 2004if (lcmd != lcmd_buf ) { 2005xfree (lcmd ); 2006 } 2007return ; 2008 } 2009if (lcmd != lcmd_buf ) { 2010xfree (lcmd ); 2011 } 2012if (nlua_pcall (lstate ,0 ,1 )) { 2013nlua_error (lstate ,_ ("E5110: Lua: %.*s" )); 2014return ; 2015 } 2016 2017buf_T * const was_curbuf = curbuf ; 2018 2019for (linenr_T l = eap -> line1 ;l <=eap -> line2 ;l ++ ) { 2020// Check the line number, the command may have deleted lines. 2021if (l > curbuf -> b_ml .ml_line_count ) { 2022break ; 2023 } 2024 2025lua_pushvalue (lstate ,-1 ); 2026const char * const old_line = ml_get_buf (curbuf ,l ); 2027// Get length of old_line here as calling Lua code may free it. 2028const colnr_T old_line_len = ml_get_buf_len (curbuf ,l ); 2029lua_pushstring (lstate ,old_line ); 2030lua_pushnumber (lstate , (lua_Number )l ); 2031if (nlua_pcall (lstate ,2 ,1 )) { 2032nlua_error (lstate ,_ ("E5111: Lua: %.*s" )); 2033break ; 2034 } 2035 2036// Catch the command switching to another buffer. 2037// Check the line number, the command may have deleted lines. 2038if (curbuf != was_curbuf || l > curbuf -> b_ml .ml_line_count ) { 2039break ; 2040 } 2041 2042if (lua_isstring (lstate ,-1 )) { 2043size_t new_line_len ; 2044const char * const new_line = lua_tolstring (lstate ,-1 ,& new_line_len ); 2045char * const new_line_transformed = xmemdupz (new_line ,new_line_len ); 2046for (size_t i = 0 ;i < new_line_len ;i ++ ) { 2047if (new_line_transformed [i ]== NUL ) { 2048new_line_transformed [i ]= '\n' ; 2049 } 2050 } 2051ml_replace (l ,new_line_transformed , false); 2052inserted_bytes (l ,0 ,old_line_len , (int )new_line_len ); 2053 } 2054lua_pop (lstate ,1 ); 2055 } 2056 2057lua_pop (lstate ,1 ); 2058check_cursor (curwin ); 2059redraw_curbuf_later (UPD_NOT_VALID ); 2060} 2061 2062/// Implements `:luafile`: executes Lua code from a file. 2063/// 2064/// @param eap Vimscript `:luafile {file}` command. 2065void ex_luafile (exarg_T * const eap ) 2066FUNC_ATTR_NONNULL_ALL 2067{ 2068nlua_exec_file (eap -> arg ); 2069} 2070 2071/// Executes Lua code from a file or "-" (stdin). 2072/// 2073/// Calls the Lua `loadfile` global as opposed to `luaL_loadfile` in case `loadfile` was overridden 2074/// in the user environment. 2075/// 2076/// @param path Path to the file, may be "-" (stdin) during startup. 2077/// 2078/// @return true on success, false on error (echoed) or user canceled (CTRL-c) while reading "-" 2079/// (stdin). 2080bool nlua_exec_file (const char * path ) 2081FUNC_ATTR_NONNULL_ALL 2082{ 2083lua_State * const lstate = global_lstate ; 2084if (!strequal (path ,"-" )) { 2085lua_getglobal (lstate ,"loadfile" ); 2086lua_pushstring (lstate ,path ); 2087 }else { 2088FileDescriptor stdin_dup ; 2089int error = file_open_stdin (& stdin_dup ); 2090if (error ) { 2091return false; 2092 } 2093 2094StringBuilder sb = KV_INITIAL_VALUE ; 2095kv_resize (sb ,64 ); 2096// Read all input from stdin, unless interrupted (ctrl-c). 2097while (true) { 2098if (got_int ) {// User canceled. 2099file_close (& stdin_dup , false); 2100kv_destroy (sb ); 2101return false; 2102 } 2103ptrdiff_t read_size = file_read (& stdin_dup ,IObuff ,64 ); 2104if (read_size < 0 ) {// Error. 2105file_close (& stdin_dup , false); 2106kv_destroy (sb ); 2107return false; 2108 } 2109if (read_size > 0 ) { 2110kv_concat_len (sb ,IObuff , (size_t )read_size ); 2111 } 2112if (read_size < 64 ) {// EOF. 2113break ; 2114 } 2115 } 2116kv_push (sb ,NUL ); 2117file_close (& stdin_dup , false); 2118 2119lua_getglobal (lstate ,"loadstring" ); 2120lua_pushstring (lstate ,sb .items ); 2121kv_destroy (sb ); 2122 } 2123 2124if (nlua_pcall (lstate ,1 ,2 )) { 2125nlua_error (lstate ,_ ("E5111: Lua: %.*s" )); 2126return false; 2127 } 2128 2129// loadstring() returns either: 2130// 1. nil, error 2131// 2. chunk, nil 2132 2133if (lua_isnil (lstate ,-2 )) { 2134// 1 2135nlua_error (lstate ,_ ("E5112: Lua chunk: %.*s" )); 2136assert (lua_isnil (lstate ,-1 )); 2137lua_pop (lstate ,1 ); 2138return false; 2139 } 2140 2141// 2 2142assert (lua_isnil (lstate ,-1 )); 2143lua_pop (lstate ,1 ); 2144 2145if (nlua_pcall (lstate ,0 ,0 )) { 2146nlua_error (lstate ,_ ("E5113: Lua chunk: %.*s" )); 2147return false; 2148 } 2149 2150return true; 2151} 2152 2153static garray_T expand_result_array = GA_EMPTY_INIT_VALUE ; 2154 2155/// Finds matches for Lua cmdline completion and advances xp->xp_pattern after prefix. 2156/// This should be called before xp->xp_pattern is first used. 2157void nlua_expand_pat (expand_T * xp ) 2158{ 2159lua_State * const lstate = global_lstate ; 2160int status = FAIL ; 2161 2162// [ vim ] 2163lua_getglobal (lstate ,"vim" ); 2164 2165// [ vim, vim._expand_pat ] 2166lua_getfield (lstate ,-1 ,"_expand_pat" ); 2167luaL_checktype (lstate ,-1 ,LUA_TFUNCTION ); 2168 2169// [ vim, vim._expand_pat, pat ] 2170const char * pat = xp -> xp_pattern ; 2171assert (xp -> xp_line + xp -> xp_col >=pat ); 2172ptrdiff_t patlen = xp -> xp_line + xp -> xp_col - pat ; 2173lua_pushlstring (lstate ,pat , (size_t )patlen ); 2174 2175if (nlua_pcall (lstate ,1 ,2 )!= 0 ) { 2176nlua_error (lstate ,_ ("vim._expand_pat: %.*s" )); 2177return ; 2178 } 2179 2180Error err = ERROR_INIT ; 2181 2182Arena arena = ARENA_EMPTY ; 2183ptrdiff_t prefix_len = nlua_pop_Integer (lstate ,& arena ,& err ); 2184if (ERROR_SET (& err )|| prefix_len > patlen ) { 2185 gotocleanup ; 2186 } 2187 2188Array completions = nlua_pop_Array (lstate ,& arena ,& err ); 2189if (ERROR_SET (& err )) { 2190 gotocleanup_array ; 2191 } 2192 2193ga_clear (& expand_result_array ); 2194ga_init (& expand_result_array , (int )sizeof (char * ),80 ); 2195 2196for (size_t i = 0 ;i < completions .size ;i ++ ) { 2197Object v = completions .items [i ]; 2198if (v .type != kObjectTypeString ) { 2199 gotocleanup_array ; 2200 } 2201GA_APPEND (char * ,& expand_result_array ,string_to_cstr (v .data .string )); 2202 } 2203 2204xp -> xp_pattern += prefix_len ; 2205status = OK ; 2206 2207cleanup_array : 2208arena_mem_free (arena_finish (& arena )); 2209 2210cleanup : 2211if (status == FAIL ) { 2212ga_clear (& expand_result_array ); 2213 } 2214} 2215 2216int nlua_expand_get_matches (int * num_results ,char *** results ) 2217{ 2218* results = expand_result_array .ga_data ; 2219* num_results = expand_result_array .ga_len ; 2220expand_result_array = (garray_T )GA_EMPTY_INIT_VALUE ; 2221return * num_results > 0 ; 2222} 2223 2224static int nlua_is_thread (lua_State * lstate ) 2225{ 2226lua_getfield (lstate ,LUA_REGISTRYINDEX ,"nvim.thread" ); 2227 2228return 1 ; 2229} 2230 2231/// Check if a typval dict/list originated from Lua (has a LuaRef). 2232bool nlua_is_table_from_lua (const typval_T * const arg ) 2233{ 2234if (arg -> v_type == VAR_DICT ) { 2235return arg -> vval .v_dict -> lua_table_ref != LUA_NOREF ; 2236 }else if (arg -> v_type == VAR_LIST ) { 2237return arg -> vval .v_list -> lua_table_ref != LUA_NOREF ; 2238 }else { 2239return false; 2240 } 2241} 2242 2243char * nlua_register_table_as_callable (const typval_T * const arg ) 2244{ 2245LuaRef table_ref = LUA_NOREF ; 2246if (arg -> v_type == VAR_DICT ) { 2247table_ref = arg -> vval .v_dict -> lua_table_ref ; 2248 }else if (arg -> v_type == VAR_LIST ) { 2249table_ref = arg -> vval .v_list -> lua_table_ref ; 2250 } 2251 2252if (table_ref == LUA_NOREF ) { 2253return NULL ; 2254 } 2255 2256lua_State * const lstate = global_lstate ; 2257 2258#ifndef NDEBUG 2259int top = lua_gettop (lstate ); 2260#endif 2261 2262nlua_pushref (lstate ,table_ref );// [table] 2263if (!lua_getmetatable (lstate ,-1 )) { 2264lua_pop (lstate ,1 ); 2265assert (top == lua_gettop (lstate )); 2266return NULL ; 2267 }// [table, mt] 2268 2269lua_getfield (lstate ,-1 ,"__call" );// [table, mt, mt.__call] 2270if (!lua_isfunction (lstate ,-1 )) { 2271lua_pop (lstate ,3 ); 2272assert (top == lua_gettop (lstate )); 2273return NULL ; 2274 } 2275lua_pop (lstate ,2 );// [table] 2276 2277LuaRef func = nlua_ref_global (lstate ,-1 ); 2278 2279char * name = register_luafunc (func ); 2280 2281lua_pop (lstate ,1 );// [] 2282assert (top == lua_gettop (lstate )); 2283 2284return name ; 2285} 2286 2287/// @return true to discard the key 2288bool nlua_exec_on_key (int c ,char * typed_buf ) 2289{ 2290static bool recursive = false; 2291 2292if (recursive ) { 2293return false; 2294 } 2295recursive = true; 2296 2297char buf [MB_MAXBYTES * 3 + 4 ]; 2298size_t buf_len = special_to_buf (c ,mod_mask , false,buf ); 2299vim_unescape_ks (typed_buf ); 2300 2301lua_State * const lstate = global_lstate ; 2302 2303#ifndef NDEBUG 2304int top = lua_gettop (lstate ); 2305#endif 2306 2307// [ vim ] 2308lua_getglobal (lstate ,"vim" ); 2309 2310// [ vim, vim._on_key ] 2311lua_getfield (lstate ,-1 ,"_on_key" ); 2312luaL_checktype (lstate ,-1 ,LUA_TFUNCTION ); 2313 2314// [ vim, vim._on_key, buf ] 2315lua_pushlstring (lstate ,buf ,buf_len ); 2316 2317// [ vim, vim._on_key, buf, typed_buf ] 2318lua_pushstring (lstate ,typed_buf ); 2319 2320int save_got_int = got_int ; 2321got_int = false;// avoid interrupts when the key typed is Ctrl-C 2322bool discard = false; 2323// Do not use nlua_pcall here to avoid duplicate stack trace information 2324if (lua_pcall (lstate ,2 ,1 ,0 )) { 2325nlua_error (lstate ,_ ("vim.on_key() callbacks: %.*s" )); 2326 }else { 2327if (lua_isboolean (lstate ,-1 )) { 2328discard = lua_toboolean (lstate ,-1 ); 2329 } 2330lua_pop (lstate ,1 ); 2331 } 2332got_int |=save_got_int ; 2333 2334// [ vim ] 2335lua_pop (lstate ,1 ); 2336 2337#ifndef NDEBUG 2338// [ ] 2339assert (top == lua_gettop (lstate )); 2340#endif 2341 2342recursive = false; 2343return discard ; 2344} 2345 2346/// Sets the editor "script context" during Lua execution. Used by :verbose. 2347/// @param[out] current 2348void nlua_set_sctx (sctx_T * current ) 2349{ 2350if (!script_is_lua (current -> sc_sid )) { 2351return ; 2352 } 2353 2354// This function is called after adding SOURCING_LNUM to sc_lnum. 2355// SOURCING_LNUM can sometimes be non-zero (e.g. with ETYPE_UFUNC), 2356// but it's unrelated to the line number in Lua scripts. 2357current -> sc_lnum = 0 ; 2358 2359if (p_verbose <=0 ) { 2360return ; 2361 } 2362lua_State * const lstate = active_lstate ; 2363lua_Debug * info = (lua_Debug * )xmalloc (sizeof (lua_Debug )); 2364 2365for (int level = 1 ; true;level ++ ) { 2366if (lua_getstack (lstate ,level ,info )!= 1 ) { 2367 gotocleanup ; 2368 } 2369if (lua_getinfo (lstate ,"nSl" ,info )== 0 ) { 2370 gotocleanup ; 2371 } 2372if (info -> what [0 ]== 'C' || info -> source [0 ]!= '@' ) { 2373continue ; 2374 } 2375break ; 2376 } 2377char * source_path = fix_fname (info -> source + 1 ); 2378int sid = find_script_by_name (source_path ); 2379if (sid > 0 ) { 2380xfree (source_path ); 2381 }else { 2382scriptitem_T * si = new_script_item (source_path ,& sid ); 2383si -> sn_lua = true; 2384 } 2385current -> sc_sid = sid ; 2386current -> sc_seq = -1 ; 2387current -> sc_lnum = info -> currentline ; 2388 2389cleanup : 2390xfree (info ); 2391} 2392 2393/// @param preview Invoke the callback as a |:command-preview| handler. 2394int nlua_do_ucmd (ucmd_T * cmd ,exarg_T * eap ,bool preview ) 2395{ 2396lua_State * const lstate = global_lstate ; 2397 2398nlua_pushref (lstate ,preview ?cmd -> uc_preview_luaref :cmd -> uc_luaref ); 2399 2400lua_newtable (lstate ); 2401nlua_push_eap (lstate ,eap ,& cmdmod ); 2402 2403lua_pushstring (lstate ,cmd -> uc_name ); 2404lua_setfield (lstate ,-2 ,"name" ); 2405 2406// Override count with uc_def fallback for user commands. 2407if (eap -> addr_count == 0 ) { 2408lua_pushinteger (lstate ,cmd -> uc_def ); 2409lua_setfield (lstate ,-2 ,"count" ); 2410 } 2411 2412// Override fargs for nargs=1/? (EX_NOSPC): the whole arg as one element (or empty). 2413// Other cases are handled by `nlua_push_eap`. 2414if (cmd -> uc_argt & EX_NOSPC ) { 2415lua_createtable (lstate ,1 ,0 ); 2416if ((cmd -> uc_argt & EX_NEEDARG )|| * eap -> arg != NUL ) { 2417lua_pushstring (lstate ,eap -> arg ); 2418lua_rawseti (lstate ,-2 ,1 ); 2419 } 2420lua_setfield (lstate ,-2 ,"fargs" ); 2421 } 2422 2423char nargs [2 ]; 2424if (cmd -> uc_argt & EX_EXTRA ) { 2425if (cmd -> uc_argt & EX_NOSPC ) { 2426if (cmd -> uc_argt & EX_ARGSPACE ) { 2427nargs [0 ]= '_' ; 2428 }else if (cmd -> uc_argt & EX_NEEDARG ) { 2429nargs [0 ]= '1' ; 2430 }else { 2431nargs [0 ]= '?' ; 2432 } 2433 }else if (cmd -> uc_argt & EX_NEEDARG ) { 2434nargs [0 ]= '+' ; 2435 }else { 2436nargs [0 ]= '*' ; 2437 } 2438 }else { 2439nargs [0 ]= '0' ; 2440 } 2441nargs [1 ]= NUL ; 2442lua_pushstring (lstate ,nargs ); 2443lua_setfield (lstate ,-2 ,"nargs" ); 2444 2445if (preview ) { 2446lua_pushinteger (lstate ,cmdpreview_get_ns ()); 2447 2448handle_T cmdpreview_bufnr = cmdpreview_get_bufnr (); 2449if (cmdpreview_bufnr != 0 ) { 2450lua_pushinteger (lstate ,cmdpreview_bufnr ); 2451 }else { 2452lua_pushnil (lstate ); 2453 } 2454 } 2455 2456if (nlua_pcall (lstate ,preview ?3 :1 ,preview ?1 :0 )) { 2457nlua_error (lstate ,_ ("Lua :command callback: %.*s" )); 2458return 0 ; 2459 } 2460 2461int retv = 0 ; 2462 2463if (preview ) { 2464if (lua_isnumber (lstate ,-1 )&& (retv = (int )lua_tointeger (lstate ,-1 )) >=0 && retv <=2 ) { 2465lua_pop (lstate ,1 ); 2466 }else { 2467retv = 0 ; 2468 } 2469 } 2470 2471return retv ; 2472} 2473 2474/// String representation of a Lua function reference 2475/// 2476/// @return Allocated string 2477char * nlua_funcref_str (LuaRef ref ,Arena * arena ,bool show_ref ) 2478{ 2479lua_State * const lstate = global_lstate ; 2480 2481if (!lua_checkstack (lstate ,1 )) { 2482 gotoplain ; 2483 } 2484nlua_pushref (lstate ,ref ); 2485if (!lua_isfunction (lstate ,-1 )) { 2486lua_pop (lstate ,1 ); 2487 gotoplain ; 2488 } 2489 2490lua_Debug ar ; 2491if (lua_getinfo (lstate ,">S" ,& ar )&& * ar .source == '@' && ar .linedefined >=0 ) { 2492char * src = home_replace_save (NULL ,ar .source + 1 ); 2493String str = show_ref ?arena_printf (arena ,"<Lua %d: %s:%d>" ,ref ,src ,ar .linedefined ) 2494 :arena_printf (arena ,"<Lua %s:%d>" ,src ,ar .linedefined ); 2495xfree (src ); 2496return str .data ; 2497 } 2498 2499plain : {} 2500return show_ref ?arena_printf (arena ,"<Lua %d>" ,ref ).data :arena_printf (arena ,"<Lua>" ).data ; 2501} 2502 2503/// Execute the vim._core.defaults module to set up default mappings and autocommands 2504void nlua_init_defaults (void ) 2505{ 2506lua_State * const L = global_lstate ; 2507assert (L ); 2508 2509lua_getglobal (L ,"require" ); 2510lua_pushstring (L ,"vim._core.defaults" ); 2511if (nlua_pcall (L ,1 ,0 )) { 2512fprintf (stderr ,"%s\n" ,lua_tostring (L ,-1 )); 2513 } 2514} 2515 2516/// check lua function exist 2517bool nlua_func_exists (const char * lua_funcname ) 2518{ 2519MAXSIZE_TEMP_ARRAY (args ,1 ); 2520size_t length = strlen (lua_funcname )+ 8 ; 2521char * str = xmalloc (length ); 2522vim_snprintf (str ,length ,"return %s" ,lua_funcname ); 2523ADD_C (args ,CSTR_AS_OBJ (str )); 2524Error err = ERROR_INIT ; 2525Object result = NLUA_EXEC_STATIC ("return type(loadstring(...)()) == 'function'" ,args , 2526kRetNilBool ,NULL ,& err ); 2527xfree (str ); 2528 2529api_clear_error (& err ); 2530return LUARET_TRUTHY (result ); 2531}