robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
71.3 KiB2531 linesraw
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 {
93  Error err;
94  String lua_err_str;
95} LuaError;
96
97typedef struct {
98  char *name;
99  const uint8_t *data;
100  size_t size;
101} ModuleDef;
102
103typedef struct {
104  LuaRef getline;  ///< Lua function returning the next input line, or nil at EOF.
105  bool 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{
123  lua_newtable(lstate);
124
125  lua_pushinteger(lstate, cmod->cmod_tab - 1);
126  lua_setfield(lstate, -2, "tab");
127
128  lua_pushinteger(lstate, cmod->cmod_verbose - 1);
129  lua_setfield(lstate, -2, "verbose");
130
131  if (cmod->cmod_split & WSP_ABOVE) {
132    lua_pushstring(lstate, "aboveleft");
133  } else if (cmod->cmod_split & WSP_BELOW) {
134    lua_pushstring(lstate, "belowright");
135  } else if (cmod->cmod_split & WSP_TOP) {
136    lua_pushstring(lstate, "topleft");
137  } else if (cmod->cmod_split & WSP_BOT) {
138    lua_pushstring(lstate, "botright");
139  } else {
140    lua_pushstring(lstate, "");
141  }
142  lua_setfield(lstate, -2, "split");
143
144  lua_pushboolean(lstate, cmod->cmod_split & WSP_VERT);
145  lua_setfield(lstate, -2, "vertical");
146  lua_pushboolean(lstate, cmod->cmod_split & WSP_HOR);
147  lua_setfield(lstate, -2, "horizontal");
148  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_SILENT);
149  lua_setfield(lstate, -2, "silent");
150  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_ERRSILENT);
151  lua_setfield(lstate, -2, "emsg_silent");
152  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_UNSILENT);
153  lua_setfield(lstate, -2, "unsilent");
154  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_SANDBOX);
155  lua_setfield(lstate, -2, "sandbox");
156  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_NOAUTOCMD);
157  lua_setfield(lstate, -2, "noautocmd");
158  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_BROWSE);
159  lua_setfield(lstate, -2, "browse");
160  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_CONFIRM);
161  lua_setfield(lstate, -2, "confirm");
162  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_HIDE);
163  lua_setfield(lstate, -2, "hide");
164  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_KEEPALT);
165  lua_setfield(lstate, -2, "keepalt");
166  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_KEEPJUMPS);
167  lua_setfield(lstate, -2, "keepjumps");
168  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_KEEPMARKS);
169  lua_setfield(lstate, -2, "keepmarks");
170  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_KEEPPATTERNS);
171  lua_setfield(lstate, -2, "keeppatterns");
172  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_LOCKMARKS);
173  lua_setfield(lstate, -2, "lockmarks");
174  lua_pushboolean(lstate, cmod->cmod_flags & CMOD_NOSWAPFILE);
175  lua_setfield(lstate, -2, "noswapfile");
176
177  // ":filter[!] /pattern/" modifier (same shape as `nvim_parse_cmd().mods.filter`).
178  lua_newtable(lstate);
179  lua_pushstring(lstate, cmod->cmod_filter_pat ? cmod->cmod_filter_pat : "");
180  lua_setfield(lstate, -2, "pattern");
181  lua_pushboolean(lstate, cmod->cmod_filter_force);
182  lua_setfield(lstate, -2, "force");
183  lua_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.
190  if (!IS_USER_CMDIDX(eap->cmdidx) && eap->cmdidx < CMD_SIZE) {
191    lua_pushstring(lstate, get_command_name(NULL, eap->cmdidx));
192    lua_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.
199  char mods_buf[200] = { 0 };
200  uc_mods(mods_buf, cmod, false);
201  lua_pushstring(lstate, mods_buf);
202  lua_setfield(lstate, -2, "mods");
203
204  // Structured form of `mods`.
205  nlua_push_cmdmod(lstate, cmod);
206  lua_setfield(lstate, -2, "smods");
207
208  lua_pushstring(lstate, eap->arg);
209  lua_setfield(lstate, -2, "args");
210
211  lua_pushboolean(lstate, eap->forceit);
212  lua_setfield(lstate, -2, "bang");
213
214  lua_pushinteger(lstate, eap->line1);
215  lua_setfield(lstate, -2, "line1");
216
217  lua_pushinteger(lstate, eap->line2);
218  lua_setfield(lstate, -2, "line2");
219
220  lua_pushinteger(lstate, eap->addr_count);
221  lua_setfield(lstate, -2, "range");
222
223  lua_pushinteger(lstate, eap->line2);
224  lua_setfield(lstate, -2, "count");
225
226  char reg[2] = { (char)eap->regname, NUL };
227  lua_pushstring(lstate, reg);
228  lua_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`.
233  if (eap->args != NULL) {
234    lua_createtable(lstate, (int)eap->argc, 0);
235    for (size_t i = 0; i < eap->argc; i++) {
236      lua_pushlstring(lstate, eap->args[i], eap->arglens[i]);
237      lua_rawseti(lstate, -2, (int)i + 1);
238    }
239    lua_setfield(lstate, -2, "fargs");
240  } else {
241    lua_newtable(lstate);
242    size_t length = strlen(eap->arg);
243    if (length > 0) {
244      size_t end = 0;
245      size_t len = 0;
246      int i = 1;
247      char *buf = xcalloc(length, sizeof(char));
248      bool done = false;
249      while (!done) {
250        done = uc_split_args_iter(eap->arg, length, &end, buf, &len);
251        if (len > 0) {
252          lua_pushlstring(lstate, buf, len);
253          lua_rawseti(lstate, -2, i);
254          i++;
255        }
256      }
257      xfree(buf);
258    }
259    lua_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 {
269  kCallback,
270  kThread,
271  kThreadCallback,
272} luv_err_t;
273
274lua_State *get_global_lstate(void)
275{
276  return 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)
287  FUNC_ATTR_NONNULL_RET
288{
289  if (lua_type(lstate, -1) != LUA_TSTRING) {
290    lua_getglobal(lstate, "tostring");
291    lua_pushvalue(lstate, -2);
292    if (lua_pcall(lstate, 1, 1, 0) || lua_type(lstate, -1) != LUA_TSTRING) {
293      lua_pop(lstate, 1);
294      lua_pushstring(lstate, "[UNPRINTABLE ERROR]");
295    }
296    lua_replace(lstate, -2);
297  }
298
299  return 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)
307  FUNC_ATTR_NONNULL_ALL
308{
309  size_t len;
310  const char *str = nlua_get_error(lstate, &len);
311
312  msg_ext_no_fast();
313  semsg_multiline("lua_error", msg, (int)len, str);
314
315  lua_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{
321  return 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
333  lua_getglobal(lstate, "debug");
334  if (lua_istable(lstate, -1)) {
335    lua_getfield(lstate, -1, "traceback");
336    lua_remove(lstate, -2);
337  }
338  bool no_traceback = !lua_isfunction(lstate, -1);  // `_G.debug.traceback` is a function?
339  if (no_traceback) {
340    lua_pop(lstate, 1);
341    lua_pushcfunction(lstate, nlua_no_traceback);
342  }
343  lua_insert(lstate, -2 - nargs);
344  int pre_top = lua_gettop(lstate);
345  int status = lua_pcall(lstate, nargs, nresults, -2 - nargs);
346  if (status) {
347    lua_remove(lstate, -2);
348    if (no_traceback && status == LUA_ERRRUN && lua_isstring(lstate, -1)) {
349      lua_pushliteral(lstate, "\nNo traceback: debug.traceback is not a function");
350      lua_concat(lstate, 2);
351    }
352  } else {
353    if (nresults == LUA_MULTRET) {
354      nresults = lua_gettop(lstate) - (pre_top - nargs - 1);
355    }
356    lua_remove(lstate, -1 - nresults);
357  }
358  return status;
359}
360
361static void nlua_luv_error_event(void **argv)
362{
363  char *error = (char *)argv[0];
364  luv_err_t type = (luv_err_t)(intptr_t)argv[1];
365  switch (type) {
366  case kCallback:
367    msg_ext_no_fast();
368    semsg_multiline("lua_error", "Lua callback:\n%s", error);
369    break;
370  case kThread:
371    semsg_multiline("lua_error", "Luv thread:\n%s", error);
372    break;
373  case kThreadCallback:
374    semsg_multiline("lua_error", "Luv callback, thread:\n%s", error);
375    break;
376  default:
377    break;
378  }
379  xfree(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)
385  FUNC_ATTR_NONNULL_ALL
386{
387  int retval;
388
389  in_fast_callback++;
390
391  int top = lua_gettop(lstate);
392  int status = nlua_pcall(lstate, nargs, nresult);
393  if (status) {
394    if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT)) {
395      // consider out of memory errors unrecoverable, just like xmalloc()
396      preserve_exit(e_outofmem);
397    }
398
399    size_t len;
400    const char *error = nlua_get_error(lstate, &len);
401
402    multiqueue_put(main_loop.events, nlua_luv_error_event,
403                   error != NULL ? xstrdup(error) : NULL, (void *)(intptr_t)kCallback);
404    lua_pop(lstate, 1);  // error message
405    retval = -status;
406  } else {  // LUA_OK
407    if (nresult == LUA_MULTRET) {
408      nresult = lua_gettop(lstate) - top + nargs + 1;
409    }
410    retval = nresult;
411  }
412
413  in_fast_callback--;
414  return retval;
415}
416
417static int nlua_luv_thread_cb_cfpcall(lua_State *lstate, int nargs, int nresult, int flags)
418{
419  return 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)
423  FUNC_ATTR_NONNULL_ALL
424{
425  return 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)
429  FUNC_ATTR_NONNULL_ARG(1, 2)
430{
431  lua_pushcfunction(lstate, func);
432  lua_pushlightuserdata(lstate, ud);
433  int retval = nlua_luv_thread_cfpcall(lstate, 1, 0, flags);
434  return retval;
435}
436
437static int nlua_luv_thread_common_cfpcall(lua_State *lstate, int nargs, int nresult, int flags,
438                                          bool is_callback)
439  FUNC_ATTR_NONNULL_ALL
440{
441  int retval;
442
443  int top = lua_gettop(lstate);
444  int status = lua_pcall(lstate, nargs, nresult, 0);
445  if (status) {
446    if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT)) {
447      // Terminate this thread, as the main thread may be able to continue
448      // execution.
449      fprintf(stderr, "%s\n", e_outofmem);
450      lua_close(lstate);
451#ifdef MSWIN
452      ExitThread(0);
453#else
454      pthread_exit(0);
455#endif
456    }
457    size_t len;
458    const char *error = nlua_get_error(lstate, &len);
459    loop_schedule_deferred(&main_loop,
460                           event_create(nlua_luv_error_event,
461                                        xmemdupz(error, len),
462                                        (void *)(intptr_t)(is_callback
463                                                           ? kThreadCallback
464                                                           : kThread)));
465    lua_pop(lstate, 1);  // error message
466    retval = -status;
467  } else {  // LUA_OK
468    if (nresult == LUA_MULTRET) {
469      nresult = lua_gettop(lstate) - top + nargs + 1;
470    }
471    retval = nresult;
472  }
473
474  return retval;
475}
476
477static int nlua_thr_api_nvim__get_runtime(lua_State *lstate)
478{
479  if (lua_gettop(lstate) != 3) {
480    return luaL_error(lstate, "Expected 3 arguments");
481  }
482
483  luaL_checktype(lstate, -1, LUA_TTABLE);
484  lua_getfield(lstate, -1, "is_lua");
485  if (!lua_isboolean(lstate, -1)) {
486    return luaL_error(lstate, "is_lua is not a boolean");
487  }
488  bool is_lua = lua_toboolean(lstate, -1);
489  lua_pop(lstate, 2);
490
491  luaL_checktype(lstate, -1, LUA_TBOOLEAN);
492  bool all = lua_toboolean(lstate, -1);
493  lua_pop(lstate, 1);
494
495  Error 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.
499  const Array pat = nlua_pop_Array(lstate, NULL, &err);
500  if (ERROR_SET(&err)) {
501    luaL_where(lstate, 1);
502    lua_pushstring(lstate, err.msg);
503    api_clear_error(&err);
504    lua_concat(lstate, 2);
505    return lua_error(lstate);
506  }
507
508  ArrayOf(String) ret = runtime_get_named_thread(is_lua, pat, all);
509  nlua_push_Array(lstate, ret, kNluaPushSpecial);
510  api_free_array(ret);
511  api_free_array(pat);
512
513  return 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{
529  int i = 0;
530  lua_newtable(L);  // _G.arg
531
532  if (lua_arg0 > 0) {
533    lua_pushstring(L, argv[lua_arg0 - 1]);
534    lua_rawseti(L, -2, 0);  // _G.arg[0] = "foo.lua"
535
536    for (; i + lua_arg0 < argc; i++) {
537      lua_pushstring(L, argv[i + lua_arg0]);
538      lua_rawseti(L, -2, i + 1);  // _G.arg[i+1] = "--foo"
539    }
540  }
541
542  lua_setglobal(L, "arg");
543  return i;
544}
545
546static void nlua_schedule_event(void **argv)
547{
548  LuaRef cb = (LuaRef)(ptrdiff_t)argv[0];
549  uint32_t ns_id = (uint32_t)(ptrdiff_t)argv[1];
550  lua_State *const lstate = global_lstate;
551  nlua_pushref(lstate, cb);
552  nlua_unref_global(lstate, cb);
553
554  // Don't impose textlock restrictions upon UI event handlers.
555  int save_expr_map_lock = expr_map_lock;
556  int save_textlock = textlock;
557  expr_map_lock = ns_id > 0 ? 0 : expr_map_lock;
558  textlock = ns_id > 0 ? 0 : textlock;
559  if (nlua_pcall(lstate, 0, 0)) {
560    nlua_error(lstate, _("vim.schedule callback: %.*s"));
561    ui_remove_cb(ns_id, true);
562  }
563  expr_map_lock = save_expr_map_lock;
564  textlock = 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)
571  FUNC_ATTR_NONNULL_ALL
572{
573  if (lua_type(lstate, 1) != LUA_TFUNCTION) {
574    lua_pushliteral(lstate, "vim.schedule: expected function");
575    return lua_error(lstate);
576  }
577
578  lua_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.
581  if (main_loop.closing) {
582    lua_pushliteral(lstate, "main loop is closing");
583    return 2;
584  }
585
586  LuaRef cb = nlua_ref_global(lstate, 1);
587  // Pass along UI event handler to disable on error.
588  multiqueue_put(main_loop.events, nlua_schedule_event, (void *)(ptrdiff_t)cb,
589                 (void *)(ptrdiff_t)ui_event_ns_id);
590  lua_pushnil(lstate);
591  return 2;
592}
593
594static int nlua_loop_poll(lua_State *lstate)
595  FUNC_ATTR_NONNULL_ALL
596{
597  int64_t timeout = (int64_t)luaL_checkinteger(lstate, 1);
598  bool fast_only = lua_toboolean(lstate, 2);
599
600  MultiQueue *loop_events = fast_only ? main_loop.fast_events : main_loop.events;
601  LOOP_PROCESS_EVENTS(&main_loop, loop_events, timeout);
602
603  return 0;
604}
605
606static int nlua_ui_flush(lua_State *lstate)
607  FUNC_ATTR_NONNULL_ALL
608{
609  ui_flush();
610  return 0;
611}
612
613static int nlua_check_interrupt(lua_State *lstate)
614  FUNC_ATTR_NONNULL_ALL
615{
616  bool interrupted = got_int;
617  if (got_int) {
618    got_int = false;
619    vgetc();
620  }
621
622  lua_pushboolean(lstate, interrupted);
623  return 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{
629  ExDocmdCookie *ecd = cookie;
630  lua_State *lstate = global_lstate;
631  nlua_pushref(lstate, ecd->getline);
632  if (nlua_pcall(lstate, 0, 1)) {
633    nlua_error(lstate, _("Error executing Ex-mode line getter: %.*s"));
634    return NULL;
635  }
636  if (lua_type(lstate, -1) != LUA_TSTRING) {  // nil: EOF.
637    lua_pop(lstate, 1);
638    return NULL;
639  }
640  char *line = xstrdup(lua_tostring(lstate, -1));
641  lua_pop(lstate, 1);
642  ecd->got_line = true;
643  return 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)
650  FUNC_ATTR_NONNULL_ALL
651{
652  luaL_checktype(lstate, 1, LUA_TFUNCTION);
653  ExDocmdCookie cookie = { .getline = nlua_ref_global(lstate, 1) };
654  msg_scroll = true;
655  need_wait_return = false;
656  no_wait_return++;  // Don't wait for return, e.g. after "-V1" messages.
657  do_cmdline(NULL, nlua_ex_getline, &cookie, 0);
658  no_wait_return--;
659  nlua_unref_global(lstate, cookie.getline);
660  lua_pushboolean(lstate, cookie.got_line);
661  return 1;
662}
663
664static int nlua_os_exit(lua_State *lstate)
665{
666  if (in_fast_callback > 0) {
667    return luaL_error(lstate, e_fast_api_disabled, "os.exit");
668  }
669
670  int status = 0;
671  if (lua_gettop(lstate) >= 1 && !lua_isnil(lstate, 1)) {
672    status = lua_isboolean(lstate, 1) ? (lua_toboolean(lstate, 1) ? 0 : 1)
673                                      : (int)luaL_checkinteger(lstate, 1);
674  }
675  getout(status);
676  return 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)
680  FUNC_ATTR_NONNULL_ALL
681{
682  nlua_ref_state_t *ref_state = lua_newuserdata(lstate, sizeof(*ref_state));
683  CLEAR_POINTER(ref_state);
684  ref_state->nil_ref = LUA_NOREF;
685  ref_state->empty_dict_ref = LUA_NOREF;
686  if (!is_thread) {
687    nlua_global_refs = ref_state;
688  }
689  return ref_state;
690}
691
692static nlua_ref_state_t *nlua_get_ref_state(lua_State *lstate)
693  FUNC_ATTR_NONNULL_ALL
694{
695  lua_getfield(lstate, LUA_REGISTRYINDEX, "nlua.ref_state");
696  nlua_ref_state_t *ref_state = lua_touserdata(lstate, -1);
697  lua_pop(lstate, 1);
698
699  return ref_state;
700}
701
702LuaRef nlua_get_nil_ref(lua_State *lstate)
703  FUNC_ATTR_NONNULL_ALL
704{
705  nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
706  return ref_state->nil_ref;
707}
708
709LuaRef nlua_get_empty_dict_ref(lua_State *lstate)
710  FUNC_ATTR_NONNULL_ALL
711{
712  nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
713  return ref_state->empty_dict_ref;
714}
715
716int nlua_get_global_ref_count(void)
717{
718  return nlua_global_refs->ref_count;
719}
720
721static void nlua_common_vim_init(lua_State *lstate, bool is_thread)
722  FUNC_ATTR_NONNULL_ARG(1)
723{
724  nlua_ref_state_t *ref_state = nlua_new_ref_state(lstate, is_thread);
725  lua_setfield(lstate, LUA_REGISTRYINDEX, "nlua.ref_state");
726
727  // vim.is_thread
728  lua_pushboolean(lstate, is_thread);
729  lua_setfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
730  lua_pushcfunction(lstate, &nlua_is_thread);
731  lua_setfield(lstate, -2, "is_thread");
732
733  // vim._core
734  lua_createtable(lstate, 0, 0);
735  lua_setfield(lstate, -2, "_core");
736
737  // vim.NIL
738  lua_newuserdata(lstate, 0);
739  lua_createtable(lstate, 0, 0);
740  lua_pushcfunction(lstate, &nlua_nil_tostring);
741  lua_setfield(lstate, -2, "__tostring");
742  lua_pushcfunction(lstate, &nlua_nil_index);
743  lua_setfield(lstate, -2, "__index");
744  lua_pushcfunction(lstate, &nlua_nil_index);
745  lua_setfield(lstate, -2, "__newindex");
746  lua_setmetatable(lstate, -2);
747  ref_state->nil_ref = nlua_ref(lstate,  ref_state, -1);
748  lua_pushvalue(lstate, -1);
749  lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.NIL");
750  lua_setfield(lstate, -2, "NIL");
751
752  // vim._empty_dict_mt
753  lua_createtable(lstate, 0, 0);
754  lua_pushcfunction(lstate, &nlua_empty_dict_tostring);
755  lua_setfield(lstate, -2, "__tostring");
756  ref_state->empty_dict_ref = nlua_ref(lstate, ref_state, -1);
757  lua_pushvalue(lstate, -1);
758  lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.empty_dict");
759  lua_setfield(lstate, -2, "_empty_dict_mt");
760
761  // vim.uv
762  if (is_thread) {
763    luv_set_callback(lstate, nlua_luv_thread_cb_cfpcall);
764    luv_set_thread(lstate, nlua_luv_thread_cfpcall);
765    luv_set_cthread(lstate, nlua_luv_thread_cfcpcall);
766  } else {
767    luv_set_loop(lstate, &main_loop.uv);
768    luv_set_callback(lstate, nlua_fast_cfpcall);
769  }
770  luaopen_luv(lstate);
771  lua_pushvalue(lstate, -1);
772  lua_setfield(lstate, -3, "uv");
773
774  lua_pushvalue(lstate, -1);
775  lua_setfield(lstate, -3, "loop");  // deprecated
776
777  // package.loaded.luv = vim.uv
778  // otherwise luv will be reinitialized when require'luv'
779  lua_getglobal(lstate, "package");
780  lua_getfield(lstate, -1, "loaded");
781  lua_pushvalue(lstate, -3);
782  lua_setfield(lstate, -2, "luv");
783  lua_pop(lstate, 3);
784}
785
786static int nlua_module_preloader(lua_State *lstate)
787{
788  size_t i = (size_t)lua_tointeger(lstate, lua_upvalueindex(1));
789  ModuleDef def = builtin_modules[i];
790  if (luaL_loadbuffer(lstate, (const char *)def.data, def.size - 1, NULL)) {
791    return lua_error(lstate);
792  }
793
794  lua_call(lstate, 0, 1);  // propagates error to caller
795  return 1;
796}
797
798static bool nlua_init_packages(lua_State *lstate)
799  FUNC_ATTR_NONNULL_ALL
800{
801  // put builtin packages in preload
802  lua_getglobal(lstate, "package");  // [package]
803  lua_getfield(lstate, -1, "preload");  // [package, preload]
804  for (size_t i = 0; i < ARRAY_SIZE(builtin_modules); i++) {
805    ModuleDef def = builtin_modules[i];
806    lua_pushinteger(lstate, (lua_Integer)i);  // [package, preload, i]
807    lua_pushcclosure(lstate, nlua_module_preloader, 1);  // [package, preload, cclosure]
808    lua_setfield(lstate, -2, def.name);  // [package, preload]
809
810    if (nlua_disable_preload && strequal(def.name, "vim.inspect")) {
811      break;
812    }
813  }
814
815  lua_pop(lstate, 2);  // []
816
817  lua_getglobal(lstate, "require");
818  lua_pushstring(lstate, "vim._init_packages");
819  if (nlua_pcall(lstate, 1, 0)) {
820    fprintf(stderr, "%s\n", lua_tostring(lstate, -1));
821    return false;
822  }
823
824  return true;
825}
826
827/// "vim.ui_attach(ns_id, {ext_foo=true}, cb)" function
828static int nlua_ui_attach(lua_State *lstate)
829  FUNC_ATTR_NONNULL_ALL
830{
831  uint32_t ns_id = (uint32_t)luaL_checkinteger(lstate, 1);
832
833  if (!ns_initialized(ns_id)) {
834    return luaL_error(lstate, "invalid ns_id");
835  }
836  if (!lua_istable(lstate, 2)) {
837    return luaL_error(lstate, "opts must be a table");
838  }
839  if (!lua_isfunction(lstate, 3)) {
840    return luaL_error(lstate, "callback must be a Lua function");
841  }
842
843  bool ext_widgets[kUIGlobalCount] = { false };
844  bool tbl_has_true_val = false;
845
846  lua_pushvalue(lstate, 2);
847  lua_pushnil(lstate);
848  while (lua_next(lstate, -2)) {
849    // [dict, key, val]
850    size_t len;
851    const char *s = lua_tolstring(lstate, -2, &len);
852    bool val = lua_toboolean(lstate, -1);
853
854    if (strequal(s, "set_cmdheight")) {
855      ui_refresh_cmdheight = val;
856      goto ok;
857    } else {
858      for (size_t i = 0; i < kUIGlobalCount; i++) {
859        if (strequal(s, ui_ext_names[i])) {
860          if (val) {
861            tbl_has_true_val = true;
862          }
863          ext_widgets[i] = val;
864          goto ok;
865        }
866      }
867    }
868
869    return luaL_error(lstate, "Unexpected key: %s", s);
870ok:
871    lua_pop(lstate, 1);
872  }
873
874  if (!tbl_has_true_val) {
875    return luaL_error(lstate, "opts table must contain at least one 'true' ext_widget");
876  }
877
878  LuaRef ui_event_cb = nlua_ref_global(lstate, 3);
879  ui_add_cb(ns_id, ui_event_cb, ext_widgets);
880  ui_refresh_cmdheight = true;
881  return 0;
882}
883
884/// "vim.ui_detach(ns_id)" function
885static int nlua_ui_detach(lua_State *lstate)
886  FUNC_ATTR_NONNULL_ALL
887{
888  uint32_t ns_id = (uint32_t)luaL_checkinteger(lstate, 1);
889
890  if (!ns_initialized(ns_id)) {
891    return luaL_error(lstate, "invalid ns_id");
892  }
893
894  ui_remove_cb(ns_id, false);
895  return 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{
903  // print
904  lua_pushcfunction(lstate, &nlua_print);
905  lua_setglobal(lstate, "print");
906
907  // debug.debug
908  lua_getglobal(lstate, "debug");
909  lua_pushcfunction(lstate, &nlua_debug);
910  lua_setfield(lstate, -2, "debug");
911  lua_pop(lstate, 1);
912
913#ifdef MSWIN
914  // os.getenv
915  lua_getglobal(lstate, "os");
916  lua_pushcfunction(lstate, &nlua_getenv);
917  lua_setfield(lstate, -2, "getenv");
918  lua_pop(lstate, 1);
919#endif
920
921  // os.exit()
922  lua_getglobal(lstate, "os");
923  lua_pushcfunction(lstate, &nlua_os_exit);
924  lua_setfield(lstate, -2, "exit");
925  lua_pop(lstate, 1);
926
927  // vim
928  lua_newtable(lstate);
929
930  // vim.api
931  nlua_add_api_functions(lstate);
932
933  // vim.types, vim.type_idx, vim.val_idx
934  nlua_init_types(lstate);
935
936  // schedule
937  lua_pushcfunction(lstate, &nlua_schedule);
938  lua_setfield(lstate, -2, "schedule");
939
940  // in_fast_event
941  lua_pushcfunction(lstate, &nlua_in_fast_event);
942  lua_setfield(lstate, -2, "in_fast_event");
943
944  // call
945  lua_pushcfunction(lstate, &nlua_call);
946  lua_setfield(lstate, -2, "call");
947
948  // rpcrequest
949  lua_pushcfunction(lstate, &nlua_rpcrequest);
950  lua_setfield(lstate, -2, "rpcrequest");
951
952  // rpcnotify
953  lua_pushcfunction(lstate, &nlua_rpcnotify);
954  lua_setfield(lstate, -2, "rpcnotify");
955
956  // ui_attach
957  lua_pushcfunction(lstate, &nlua_ui_attach);
958  lua_setfield(lstate, -2, "ui_attach");
959
960  // ui_detach
961  lua_pushcfunction(lstate, &nlua_ui_detach);
962  lua_setfield(lstate, -2, "ui_detach");
963
964  nlua_common_vim_init(lstate, false);
965
966  // Bindings for `vim.wait()`.
967  lua_getfield(lstate, -1, "_core");
968  lua_pushcfunction(lstate, &nlua_loop_poll);
969  lua_setfield(lstate, -2, "loop_poll");
970  lua_pushcfunction(lstate, &nlua_ui_flush);
971  lua_setfield(lstate, -2, "ui_flush");
972  lua_pushcfunction(lstate, &nlua_check_interrupt);
973  lua_setfield(lstate, -2, "check_interrupt");
974
975  // Misc vim._core bindings.
976  lua_pushcfunction(lstate, &nlua_ex_docmd);
977  lua_setfield(lstate, -2, "ex_docmd");
978  lua_pop(lstate, 1);
979
980  // patch require() (only for --startuptime)
981  if (time_fd != NULL) {
982    lua_getglobal(lstate, "require");
983    // Must do this after nlua_common_vim_init where nlua_global_refs is initialized.
984    require_ref = nlua_ref_global(lstate, -1);
985    lua_pop(lstate, 1);
986    lua_pushcfunction(lstate, &nlua_require);
987    lua_setglobal(lstate, "require");
988  }
989
990  // internal vim._treesitter... API
991  nlua_treesitter_init(lstate);
992
993  nlua_state_add_stdlib(lstate, false);
994
995  lua_setglobal(lstate, "vim");
996
997  if (!nlua_init_packages(lstate)) {
998    return false;
999  }
1000
1001  return 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
1008  if (os_env_exists("NVIM_LUA_NOTRACK", true)) {
1009    nlua_track_refs = true;
1010  }
1011#endif
1012
1013  lua_State *lstate = luaL_newstate();
1014  if (lstate == NULL) {
1015    fprintf(stderr, _("E970: Failed to initialize Lua interpreter\n"));
1016    os_exit(1);
1017  }
1018  luaL_openlibs(lstate);
1019  if (!nlua_state_init(lstate)) {
1020    fprintf(stderr, _("E970: Failed to initialize builtin Lua modules\n"));
1021#ifdef EXITFREE
1022    nlua_common_free_all_mem(lstate);
1023#endif
1024    os_exit(1);
1025  }
1026
1027  luv_set_thread_cb(nlua_thread_acquire_vm, nlua_common_free_all_mem);
1028  global_lstate = lstate;
1029  active_lstate = lstate;
1030  main_thread = uv_thread_self();
1031  nlua_init_argv(lstate, argv, argc, lua_arg0);
1032}
1033
1034static lua_State *nlua_thread_acquire_vm(void)
1035{
1036  return 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.
1042  const uv_thread_t self = uv_thread_self();
1043  if (uv_thread_equal(&main_thread, &self)) {
1044    runtime_search_path_validate();
1045  }
1046
1047  lua_State *lstate = luaL_newstate();
1048
1049  // Add in the lua standard libraries
1050  luaL_openlibs(lstate);
1051
1052  // print
1053  lua_pushcfunction(lstate, &nlua_print);
1054  lua_setglobal(lstate, "print");
1055
1056  lua_pushinteger(lstate, 0);
1057  lua_setfield(lstate, LUA_REGISTRYINDEX, "nlua.refcount");
1058
1059  // vim
1060  lua_newtable(lstate);
1061
1062  nlua_common_vim_init(lstate, thread);
1063
1064  nlua_state_add_stdlib(lstate, true);
1065
1066  lua_createtable(lstate, 0, 0);
1067  lua_pushcfunction(lstate, nlua_thr_api_nvim__get_runtime);
1068  lua_setfield(lstate, -2, "nvim__get_runtime");
1069  lua_setfield(lstate, -2, "api");
1070
1071  lua_setglobal(lstate, "vim");
1072
1073  nlua_init_packages(lstate);
1074
1075  lua_getglobal(lstate, "package");
1076  lua_getfield(lstate, -1, "loaded");
1077  lua_getglobal(lstate, "vim");
1078  lua_setfield(lstate, -2, "vim");
1079  lua_pop(lstate, 2);
1080
1081  return lstate;
1082}
1083
1084/// Disposes global Lua state. Idempotent, harmless if called multiple times.
1085void nlua_free_all_mem(void)
1086{
1087  if (!global_lstate) {
1088    return;
1089  }
1090  lua_State *lstate = global_lstate;
1091  global_lstate = NULL;
1092  nlua_unref_global(lstate, require_ref);
1093  nlua_common_free_all_mem(lstate);
1094  nlua_treesitter_free();
1095}
1096
1097static void nlua_common_free_all_mem(lua_State *lstate)
1098  FUNC_ATTR_NONNULL_ALL
1099{
1100  nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
1101  nlua_unref(lstate, ref_state, ref_state->nil_ref);
1102  nlua_unref(lstate, ref_state, ref_state->empty_dict_ref);
1103
1104#ifdef NLUA_TRACK_REFS
1105  if (ref_state->ref_count) {
1106    fprintf(stderr, "%d lua references were leaked!", ref_state->ref_count);
1107  }
1108
1109  if (nlua_track_refs) {
1110    // in case there are leaked luarefs, leak the associated memory
1111    // to get LeakSanitizer stacktraces on exit
1112    map_destroy(int, &ref_state->ref_markers);
1113  }
1114#endif
1115
1116  lua_close(lstate);
1117}
1118
1119static void nlua_print_event(void **argv)
1120{
1121  msg_ext_no_fast();
1122  if (msg_use_printf() && on_print.type == kCallbackNone) {
1123    msg_start();  // flush incomplete message
1124    printf("%.*s\n", (int)(intptr_t)argv[1] - 1, (char *)argv[0]);
1125    xfree(argv[0]);
1126  } else {
1127    HlMessage msg = KV_INITIAL_VALUE;
1128    HlMessageChunk chunk = { { .data = argv[0], .size = (size_t)(intptr_t)argv[1] - 1 }, 0 };
1129    kv_push(msg, chunk);
1130    bool needs_clear = false;
1131    msg_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)
1139  FUNC_ATTR_NONNULL_ALL
1140{
1141  const int nargs = lua_gettop(lstate);
1142  lua_getglobal(lstate, "tostring");
1143  const char *errmsg = NULL;
1144  size_t errmsg_len = 0;
1145  garray_T msg_ga;
1146  ga_init(&msg_ga, 1, 80);
1147  int curargidx = 1;
1148  for (; curargidx <= nargs; curargidx++) {
1149    lua_pushvalue(lstate, -1);  // tostring
1150    lua_pushvalue(lstate, curargidx);  // arg
1151    // Do not use nlua_pcall here to avoid duplicate stack trace information
1152    if (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.
1155      errmsg = nlua_get_error(lstate, &errmsg_len);
1156      goto nlua_print_error;
1157    }
1158
1159    size_t len;
1160    const char *const s = lua_tolstring(lstate, -1, &len);
1161    ga_concat_len(&msg_ga, s, len);
1162    if (curargidx < nargs) {
1163      ga_append(&msg_ga, ' ');
1164    }
1165    lua_pop(lstate, 1);
1166  }
1167  ga_append(&msg_ga, NUL);
1168
1169  lua_getfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
1170  bool is_thread = lua_toboolean(lstate, -1);
1171  lua_pop(lstate, 1);
1172
1173  if (is_thread) {
1174    loop_schedule_deferred(&main_loop,
1175                           event_create(nlua_print_event,
1176                                        msg_ga.ga_data,
1177                                        (void *)(intptr_t)msg_ga.ga_len));
1178  } else if (in_fast_callback) {
1179    multiqueue_put(main_loop.events, nlua_print_event,
1180                   msg_ga.ga_data, (void *)(intptr_t)msg_ga.ga_len);
1181  } else {
1182    nlua_print_event((void *[]){ msg_ga.ga_data, (void *)(intptr_t)msg_ga.ga_len });
1183  }
1184  return 0;
1185
1186nlua_print_error:
1187  ga_clear(&msg_ga);
1188  char *buff = xmalloc(IOSIZE);
1189  const char *fmt = _("E5114: Converting print argument #%i: %.*s");
1190  size_t len = (size_t)vim_snprintf(buff, IOSIZE, fmt, curargidx,
1191                                    (int)errmsg_len, errmsg);
1192  lua_pushlstring(lstate, buff, len);
1193  xfree(buff);
1194  return lua_error(lstate);
1195}
1196
1197/// require() for --startuptime
1198///
1199/// @param  lstate  Lua interpreter state.
1200static int nlua_require(lua_State *const lstate)
1201  FUNC_ATTR_NONNULL_ALL
1202{
1203  const char *name = luaL_checkstring(lstate, 1);
1204  lua_settop(lstate, 1);
1205  // [ name ]
1206
1207  // try cached module from package.loaded first
1208  lua_getfield(lstate, LUA_REGISTRYINDEX, "_LOADED");
1209  lua_getfield(lstate, 2, name);
1210  // [ name package.loaded module ]
1211  if (lua_toboolean(lstate, -1)) {
1212    return 1;
1213  }
1214  lua_pop(lstate, 2);
1215  // [ name ]
1216
1217  // push original require below the module name
1218  nlua_pushref(lstate, require_ref);
1219  lua_insert(lstate, 1);
1220  // [ require name ]
1221
1222  if (time_fd == NULL) {
1223    // after log file was closed, try to restore
1224    // global require to the original function...
1225    lua_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...
1229    if (lua_iscfunction(lstate, -1) && lua_tocfunction(lstate, -1) == nlua_require) {
1230      lua_pushvalue(lstate, 1);
1231      lua_setglobal(lstate, "require");
1232    }
1233    lua_pop(lstate, 1);
1234
1235    // ...and then call require directly.
1236    lua_call(lstate, 1, 1);
1237    return 1;
1238  }
1239
1240  proftime_T rel_time;
1241  proftime_T start_time;
1242  time_push(&rel_time, &start_time);
1243  int status = lua_pcall(lstate, 1, 1, 0);
1244  if (status == 0) {
1245    vim_snprintf(IObuff, IOSIZE, "require('%s')", name);
1246    time_msg(IObuff, &start_time);
1247  }
1248  time_pop(rel_time);
1249
1250  return 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)
1257  FUNC_ATTR_NONNULL_ALL
1258{
1259  const 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  };
1269  while (true) {
1270    lua_settop(lstate, 0);
1271    typval_T input;
1272    get_user_input(input_args, &input, false, false);
1273
1274    if (ui_has(kUICmdline)) {
1275      snprintf(IObuff, IOSIZE, "lua_debug> %s", input.vval.v_string);
1276      ui_ext_cmdline_block_append(0, IObuff);
1277    } else {
1278      msg_putchar('\n');  // Avoid outputting on input line.
1279    }
1280
1281    if (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) {
1285      tv_clear(&input);
1286      if (ui_has(kUICmdline)) {
1287        ui_ext_cmdline_block_leave();
1288      }
1289      return 0;
1290    }
1291
1292    if (luaL_loadbuffer(lstate, input.vval.v_string,
1293                        strlen(input.vval.v_string), "=(debug command)")) {
1294      nlua_error(lstate, _("E5115: Loading Lua debug string: %.*s"));
1295    } else if (nlua_pcall(lstate, 0, 0)) {
1296      nlua_error(lstate, _("E5116: Calling Lua debug string: %.*s"));
1297    }
1298    tv_clear(&input);
1299  }
1300  return 0;
1301}
1302
1303/// "vim.in_fast_event()" function.
1304int nlua_in_fast_event(lua_State *lstate)
1305{
1306  lua_pushboolean(lstate, in_fast_callback > 0);
1307  return 1;
1308}
1309
1310static bool viml_func_is_fast(const char *name)
1311{
1312  const EvalFuncDef *const fdef = find_internal_func(name);
1313  if (fdef) {
1314    return fdef->fast;
1315  }
1316  // Not a Vimscript function
1317  return false;
1318}
1319
1320/// "vim.call()", aka "vim.fn".
1321int nlua_call(lua_State *lstate)
1322{
1323  Error err = ERROR_INIT;
1324  size_t name_len;
1325  const char *name = luaL_checklstring(lstate, 1, &name_len);
1326  if (!nlua_is_deferred_safe() && !viml_func_is_fast(name)) {
1327    size_t length = MIN(strlen(name), 100) + sizeof("Vimscript function \"\"");
1328    vim_snprintf(IObuff, length, "Vimscript function \"%s\"", name);
1329    int ret = luaL_error(lstate, e_fast_api_disabled, IObuff);
1330    return ret;
1331  }
1332
1333  int nargs = lua_gettop(lstate) - 1;
1334  if (nargs > MAX_FUNC_ARGS) {
1335    return 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.
1340  const char *func_lua = find_internal_func_lua(name);
1341  if (func_lua) {
1342    lua_getglobal(lstate, "require");
1343    lua_pushliteral(lstate, "vim._core.vimfn");
1344    if (lua_pcall(lstate, 1, 1, 0) != 0) {
1345      return lua_error(lstate);
1346    }
1347    lua_getfield(lstate, -1, func_lua);
1348    lua_remove(lstate, -2);  // remove module table
1349    // Push args (still on the stack as Lua values).
1350    for (int j = 0; j < nargs; j++) {
1351      lua_pushvalue(lstate, j + 2);
1352    }
1353    if (lua_pcall(lstate, nargs, 1, 0) != 0) {
1354      return lua_error(lstate);
1355    }
1356    return 1;
1357  }
1358
1359  typval_T vim_args[MAX_FUNC_ARGS + 1];
1360  int i = 0;  // also used for freeing the variables
1361  for (; i < nargs; i++) {
1362    lua_pushvalue(lstate, i + 2);
1363    if (!nlua_pop_typval(lstate, &vim_args[i])) {
1364      api_set_error(&err, kErrorTypeException,
1365                    "error converting argument %d", i + 1);
1366      goto free_vim_args;
1367    }
1368  }
1369
1370  // TODO(bfredl): this should be simplified in error handling refactor
1371  force_abort = false;
1372  suppress_errthrow = false;
1373  did_throw = false;
1374  did_emsg = false;
1375
1376  typval_T rettv;
1377  funcexe_T funcexe = FUNCEXE_INIT;
1378  funcexe.fe_firstline = curwin->w_cursor.lnum;
1379  funcexe.fe_lastline = curwin->w_cursor.lnum;
1380  funcexe.fe_evaluate = true;
1381  const sctx_T save_current_sctx = api_set_sctx(LUA_INTERNAL_CALL);
1382
1383  TRY_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  });
1388  current_sctx = save_current_sctx;
1389
1390  if (!ERROR_SET(&err)) {
1391    nlua_push_typval(lstate, &rettv, 0);
1392  }
1393  tv_clear(&rettv);
1394
1395free_vim_args:
1396  while (i > 0) {
1397    tv_clear(&vim_args[--i]);
1398  }
1399  if (ERROR_SET(&err)) {
1400    lua_pushstring(lstate, err.msg);
1401    api_clear_error(&err);
1402    return lua_error(lstate);
1403  }
1404  return 1;
1405}
1406
1407static int nlua_rpcrequest(lua_State *lstate)
1408{
1409  if (!nlua_is_deferred_safe()) {
1410    return luaL_error(lstate, e_fast_api_disabled, "rpcrequest");
1411  }
1412  return nlua_rpc(lstate, true);
1413}
1414
1415static int nlua_rpcnotify(lua_State *lstate)
1416{
1417  return nlua_rpc(lstate, false);
1418}
1419
1420static int nlua_rpc(lua_State *lstate, bool request)
1421{
1422  size_t name_len;
1423  uint64_t chan_id = (uint64_t)luaL_checkinteger(lstate, 1);
1424  const char *name = luaL_checklstring(lstate, 2, &name_len);
1425  int nargs = lua_gettop(lstate) - 2;
1426  Error err = ERROR_INIT;
1427  Arena arena = ARENA_EMPTY;
1428
1429  Array args = arena_array(&arena, (size_t)nargs);
1430  for (int i = 0; i < nargs; i++) {
1431    lua_pushvalue(lstate, i + 3);
1432    ADD(args, nlua_pop_Object(lstate, false, &arena, &err));
1433    if (ERROR_SET(&err)) {
1434      goto check_err;
1435    }
1436  }
1437
1438  if (request) {
1439    ArenaMem res_mem = NULL;
1440    Object result = rpc_send_call(chan_id, name, args, &res_mem, &err);
1441    if (!ERROR_SET(&err)) {
1442      nlua_push_Object(lstate, &result, 0);
1443      arena_mem_free(res_mem);
1444    }
1445  } else {
1446    if (!rpc_send_event(chan_id, name, args)) {
1447      api_set_error(&err, kErrorTypeValidation,
1448                    "Invalid channel: %" PRIu64, chan_id);
1449    }
1450  }
1451
1452check_err:
1453  arena_mem_free(arena_finish(&arena));
1454
1455  if (ERROR_SET(&err)) {
1456    lua_pushstring(lstate, err.msg);
1457    api_clear_error(&err);
1458    return lua_error(lstate);
1459  }
1460
1461  return request ? 1 : 0;
1462}
1463
1464static int nlua_nil_tostring(lua_State *lstate)
1465{
1466  lua_pushstring(lstate, "vim.NIL");
1467  return 1;
1468}
1469
1470static int nlua_nil_index(lua_State *lstate)
1471{
1472  return luaL_error(lstate, "attempt to index vim.NIL");
1473}
1474
1475static int nlua_empty_dict_tostring(lua_State *lstate)
1476{
1477  lua_pushstring(lstate, "vim.empty_dict()");
1478  return 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{
1489  lua_pushstring(lstate, os_getenv_noalloc(luaL_checkstring(lstate, 1)));
1490  return 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{
1498  lua_pushvalue(lstate, index);
1499  LuaRef ref = luaL_ref(lstate, LUA_REGISTRYINDEX);
1500  if (ref > 0) {
1501    ref_state->ref_count++;
1502#ifdef NLUA_TRACK_REFS
1503    if (nlua_track_refs) {
1504      // dummy allocation to make LeakSanitizer track our luarefs
1505      pmap_put(int)(&ref_state->ref_markers, ref, xmalloc(3));
1506    }
1507#endif
1508  }
1509  return 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{
1517  return 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{
1523  if (ref > 0) {
1524    ref_state->ref_count--;
1525#ifdef NLUA_TRACK_REFS
1526    // NB: don't remove entry from map to track double-unref
1527    if (nlua_track_refs) {
1528      xfree(pmap_get(int)(&ref_state->ref_markers, ref));
1529    }
1530#endif
1531    luaL_unref(lstate, LUA_REGISTRYINDEX, ref);
1532  }
1533}
1534
1535void nlua_unref_global(lua_State *lstate, LuaRef ref)
1536{
1537  nlua_unref(lstate, nlua_global_refs, ref);
1538}
1539
1540void api_free_luaref(LuaRef ref)
1541{
1542  nlua_unref_global(global_lstate, ref);
1543}
1544
1545/// push a value referenced in the registry
1546void nlua_pushref(lua_State *lstate, LuaRef ref)
1547{
1548  lua_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{
1557  if (original_ref == LUA_NOREF) {
1558    return LUA_NOREF;
1559  }
1560
1561  lua_State *const lstate = global_lstate;
1562  nlua_pushref(lstate, original_ref);
1563  LuaRef new_ref = nlua_ref_global(lstate,  -1);
1564  lua_pop(lstate, 1);
1565  return 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,
1571                                 const char *name, typval_T *args, int argcount, bool special,
1572                                 typval_T *ret_tv)
1573  FUNC_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.
1577  static char lcmd_buf[IOSIZE];
1578  char *lcmd = lcmd_buf;
1579  int lcmd_len = vim_snprintf(lcmd_buf, sizeof(lcmd_buf), fmt, (int)bodylen, body);
1580  if (lcmd_len >= IOSIZE) {
1581    lcmd = xmalloc((size_t)lcmd_len + 1);
1582    vim_snprintf(lcmd, (size_t)lcmd_len + 1, fmt, (int)bodylen, body);
1583  }
1584
1585  nlua_exec_typval(lcmd, (size_t)lcmd_len, name, args, argcount, special, ret_tv);
1586
1587  if (lcmd != lcmd_buf) {
1588    xfree(lcmd);
1589  }
1590}
1591
1592/// Implements vimfn: luaeval().
1593void nlua_call_luaeval(const String str, typval_T *const arg, typval_T *const ret_tv)
1594  FUNC_ATTR_NONNULL_ALL
1595{
1596  nlua_exec_typval_fmt("local _A=select(1,...) return (%.*s)", str.data, str.size, "luaeval()", arg,
1597                       1, 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,
1602                    typval_T *ret_tv)
1603  FUNC_ATTR_NONNULL_ALL
1604{
1605  nlua_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)
1610  FUNC_ATTR_NONNULL_ALL
1611{
1612  lua_State *const lstate = global_lstate;
1613
1614  nlua_pushref(lstate, xp->xp_luaref);
1615  lua_pushstring(lstate, xp->xp_pattern);
1616  lua_pushstring(lstate, xp->xp_line);
1617  lua_pushinteger(lstate, xp->xp_col);
1618
1619  if (nlua_pcall(lstate, 3, 1)) {
1620    nlua_error(lstate, _("E5108: Lua function: %.*s"));
1621    return;
1622  }
1623
1624  nlua_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,
1629                             typval_T *const args, int argcount, bool special, typval_T *ret_tv)
1630{
1631  if (check_secure()) {
1632    if (ret_tv) {
1633      ret_tv->v_type = VAR_NUMBER;
1634      ret_tv->vval.v_number = 0;
1635    }
1636    return;
1637  }
1638
1639  lua_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.
1645  if (luaL_loadbuffer(lstate, lcmd, lcmd_len, name)) {
1646    nlua_error(lstate, _("E5107: Lua: %.*s"));
1647    return;
1648  }
1649
1650  // 2. Push typval args as Lua values. Stack: [chunk, arg1, ..., argN].
1651  PUSH_ALL_TYPVALS(lstate, args, argcount, special);
1652
1653  // 3. Call: chunk(arg1, ..., argN). Essentially loadstring().
1654  if (nlua_pcall(lstate, argcount, ret_tv ? 1 : 0)) {
1655    nlua_error(lstate, _("E5108: Lua: %.*s"));
1656    return;
1657  }
1658
1659  if (ret_tv) {
1660    nlua_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{
1667  char *code = ga_concat_strings(ga, "\n");
1668  size_t len = strlen(code);
1669  nlua_exec_typval(code, len, name, NULL, 0, false, NULL);
1670  xfree(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{
1682  lua_State *lstate = global_lstate;
1683
1684  nlua_pushref(lstate, lua_cb);
1685
1686  PUSH_ALL_TYPVALS(lstate, argvars, argcount, false);
1687
1688  if (nlua_pcall(lstate, argcount, 1)) {
1689    nlua_error(lstate, _("Lua callback: %.*s"));
1690    return FCERR_OTHER;
1691  }
1692
1693  nlua_pop_typval(lstate, rettv);
1694
1695  return 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,
1711                 Arena *arena, Error *err)
1712{
1713  lua_State *const lstate = global_lstate;
1714
1715  int top = lua_gettop(lstate);
1716  const char *name = (chunkname && chunkname[0]) ? chunkname : "<nvim>";
1717  if (luaL_loadbuffer(lstate, str.data, str.size, name)) {
1718    size_t len;
1719    const char *errstr = lua_tolstring(lstate, -1, &len);
1720    api_set_error(err, kErrorTypeValidation, "Lua: %.*s", (int)len, errstr);
1721    return NIL;
1722  }
1723
1724  for (size_t i = 0; i < args.size; i++) {
1725    nlua_push_Object(lstate, &args.items[i], 0);
1726  }
1727
1728  if (nlua_pcall(lstate, (int)args.size, 1)) {
1729    size_t len;
1730    const char *errstr = lua_tolstring(lstate, -1, &len);
1731    api_set_error(err, kErrorTypeException, "Lua: %.*s", (int)len, errstr);
1732    return NIL;
1733  }
1734
1735  return 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{
1749  int argcount = 0;
1750  for (typval_T *tv = argvars; tv->v_type != VAR_UNKNOWN; tv++) {
1751    argcount++;
1752  }
1753
1754  char buf[256];
1755  snprintf(buf, sizeof(buf), "return require('%s').%s(...)", module, func);
1756
1757  nlua_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,
1770                     typval_T *extra)
1771{
1772  lua_State *const lstate = global_lstate;
1773
1774  lua_getglobal(lstate, "require");
1775  lua_pushstring(lstate, module);
1776  if (lua_pcall(lstate, 1, 1, 0) != 0) {
1777    nlua_error(lstate, "E5108: %s");
1778    return false;
1779  }
1780  lua_getfield(lstate, -1, func);
1781  lua_remove(lstate, -2);
1782
1783  lua_newtable(lstate);
1784  nlua_push_eap(lstate, eap, cmod);
1785
1786  int nargs = 1;
1787  if (extra) {
1788    nlua_push_typval(lstate, extra, 0);
1789    nargs = 2;
1790  }
1791
1792  if (nlua_pcall(lstate, nargs, 0)) {
1793    // Not "E5108" because this is a logical/application error, not a "Lua error".
1794    emsg(lua_tostring(lstate, -1));
1795    lua_pop(lstate, 1);
1796    return false;
1797  }
1798  return true;
1799}
1800
1801/// Checks if a LuaRef refers to a function.
1802bool nlua_ref_is_function(LuaRef ref)
1803{
1804  lua_State *const lstate = global_lstate;
1805  nlua_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
1809  bool is_function = (lua_type(lstate, -1) == LUA_TFUNCTION);
1810  lua_pop(lstate, 1);
1811
1812  return 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,
1825                     Error *err)
1826{
1827  return nlua_call_ref_ctx(false, ref, name, args, mode, arena, err);
1828}
1829
1830static int mode_ret(LuaRetMode mode)
1831{
1832  return (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,
1837                         Arena *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.
1842  lua_State *const lstate = active_lstate;
1843  int top = lua_gettop(lstate);
1844  nlua_pushref(lstate, ref);
1845  int nargs = (int)args.size;
1846  if (name != NULL) {
1847    lua_pushstring(lstate, name);
1848    nargs++;
1849  }
1850  for (size_t i = 0; i < args.size; i++) {
1851    nlua_push_Object(lstate, &args.items[i], 0);
1852  }
1853
1854  if (fast) {
1855    if (nlua_fast_cfpcall(lstate, nargs, mode_ret(mode), -1) < 0) {
1856      // error is already scheduled, set anyways to convey failure.
1857      api_set_error(err, kErrorTypeException, "fast context failure");
1858      return NIL;
1859    }
1860  } else if (nlua_pcall(lstate, nargs, mode_ret(mode))) {
1861    // if err is passed, the caller will deal with the error.
1862    if (err) {
1863      size_t len;
1864      const char *errstr = lua_tolstring(lstate, -1, &len);
1865      api_set_error(err, kErrorTypeException, "Lua: %.*s", (int)len, errstr);
1866    } else {
1867      nlua_error(lstate, _("Lua callback: %.*s"));
1868    }
1869    return NIL;
1870  }
1871
1872  return 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,
1876                                   Error *err)
1877{
1878  if (mode != kRetMulti && mode != kRetMultiStack && lua_isnil(lstate, -1)) {
1879    lua_pop(lstate, 1);
1880    return NIL;
1881  }
1882  Error dummy = ERROR_INIT;
1883  Error *perr = err ? err : &dummy;
1884
1885  switch (mode) {
1886  case kRetNilBool: {
1887    bool bool_value = lua_toboolean(lstate, -1);
1888    lua_pop(lstate, 1);
1889
1890    return BOOLEAN_OBJ(bool_value);
1891  }
1892  case kRetLuaref: {
1893    LuaRef ref = nlua_ref_global(lstate, -1);
1894    lua_pop(lstate, 1);
1895
1896    return LUAREF_OBJ(ref);
1897  }
1898  case kRetObject:
1899    return nlua_pop_Object(lstate, false, arena, perr);
1900  case kRetMulti:
1901    ;
1902    int nres = lua_gettop(lstate) - pretop;
1903    Array res = arena_array(arena, (size_t)nres);
1904    for (int i = 0; i < nres; i++) {
1905      res.items[nres - i - 1] = nlua_pop_Object(lstate, false, arena, perr);
1906      if (ERROR_SET(perr)) {
1907        return NIL;
1908      }
1909    }
1910    res.size = (size_t)nres;
1911    return ARRAY_OBJ(res);
1912  case kRetMultiStack:
1913    ;
1914    return NIL;
1915  }
1916  UNREACHABLE;
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{
1923  return 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)
1930  FUNC_ATTR_NONNULL_ALL
1931{
1932  // ":{range}lua", only if no {code}
1933  if (*eap->arg == NUL) {
1934    if (eap->addr_count > 0) {
1935      cmd_source_buffer(eap, true);
1936    } else {
1937      emsg(_(e_argreq));
1938    }
1939    return;
1940  }
1941
1942  size_t len;
1943  char *code = script_get(eap, &len);
1944  if (eap->skip || code == NULL) {
1945    xfree(code);
1946    return;
1947  }
1948
1949  // ":lua {code}", ":={expr}" or ":lua ={expr}"
1950  //
1951  // When "=expr" is used transform it to "vim._print(true, expr)".
1952  if (eap->cmdidx == CMD_equal || code[0] == '=') {
1953    size_t off = (eap->cmdidx == CMD_equal) ? 0 : 1;
1954    len += sizeof("vim._print(true, )") - 1 - off;
1955    // `nlua_exec_typval` doesn't expect NUL-terminated string so `len` must end before NUL byte.
1956    char *code_buf = xmallocz(len);
1957    vim_snprintf(code_buf, len + 1, "vim._print(true, %s)", code + off);
1958    xfree(code);
1959    code = code_buf;
1960  }
1961
1962  nlua_exec_typval(code, len, ":lua", NULL, 0, false, NULL);
1963
1964  xfree(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)
1971  FUNC_ATTR_NONNULL_ALL
1972{
1973  if (u_save(eap->line1 - 1, eap->line2 + 1) == FAIL) {
1974    emsg(_("cannot save undo information"));
1975    return;
1976  }
1977  const char *const cmd = eap->arg;
1978  const size_t cmd_len = strlen(cmd);
1979
1980  lua_State *const lstate = global_lstate;
1981
1982#define DOSTART "return function(line, linenr) "
1983#define DOEND " end"
1984  const 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.
1989  static char lcmd_buf[IOSIZE];
1990  char *lcmd;
1991  if (lcmd_len < IOSIZE) {
1992    lcmd = lcmd_buf;
1993  } else {
1994    lcmd = xmalloc(lcmd_len + 1);
1995  }
1996  memcpy(lcmd, DOSTART, sizeof(DOSTART) - 1);
1997  memcpy(lcmd + sizeof(DOSTART) - 1, cmd, cmd_len);
1998  memcpy(lcmd + sizeof(DOSTART) - 1 + cmd_len, DOEND, sizeof(DOEND) - 1);
1999#undef DOSTART
2000#undef DOEND
2001
2002  if (luaL_loadbuffer(lstate, lcmd, lcmd_len, ":luado")) {
2003    nlua_error(lstate, _("E5109: Lua: %.*s"));
2004    if (lcmd != lcmd_buf) {
2005      xfree(lcmd);
2006    }
2007    return;
2008  }
2009  if (lcmd != lcmd_buf) {
2010    xfree(lcmd);
2011  }
2012  if (nlua_pcall(lstate, 0, 1)) {
2013    nlua_error(lstate, _("E5110: Lua: %.*s"));
2014    return;
2015  }
2016
2017  buf_T *const was_curbuf = curbuf;
2018
2019  for (linenr_T l = eap->line1; l <= eap->line2; l++) {
2020    // Check the line number, the command may have deleted lines.
2021    if (l > curbuf->b_ml.ml_line_count) {
2022      break;
2023    }
2024
2025    lua_pushvalue(lstate, -1);
2026    const char *const old_line = ml_get_buf(curbuf, l);
2027    // Get length of old_line here as calling Lua code may free it.
2028    const colnr_T old_line_len = ml_get_buf_len(curbuf, l);
2029    lua_pushstring(lstate, old_line);
2030    lua_pushnumber(lstate, (lua_Number)l);
2031    if (nlua_pcall(lstate, 2, 1)) {
2032      nlua_error(lstate, _("E5111: Lua: %.*s"));
2033      break;
2034    }
2035
2036    // Catch the command switching to another buffer.
2037    // Check the line number, the command may have deleted lines.
2038    if (curbuf != was_curbuf || l > curbuf->b_ml.ml_line_count) {
2039      break;
2040    }
2041
2042    if (lua_isstring(lstate, -1)) {
2043      size_t new_line_len;
2044      const char *const new_line = lua_tolstring(lstate, -1, &new_line_len);
2045      char *const new_line_transformed = xmemdupz(new_line, new_line_len);
2046      for (size_t i = 0; i < new_line_len; i++) {
2047        if (new_line_transformed[i] == NUL) {
2048          new_line_transformed[i] = '\n';
2049        }
2050      }
2051      ml_replace(l, new_line_transformed, false);
2052      inserted_bytes(l, 0, old_line_len, (int)new_line_len);
2053    }
2054    lua_pop(lstate, 1);
2055  }
2056
2057  lua_pop(lstate, 1);
2058  check_cursor(curwin);
2059  redraw_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)
2066  FUNC_ATTR_NONNULL_ALL
2067{
2068  nlua_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)
2081  FUNC_ATTR_NONNULL_ALL
2082{
2083  lua_State *const lstate = global_lstate;
2084  if (!strequal(path, "-")) {
2085    lua_getglobal(lstate, "loadfile");
2086    lua_pushstring(lstate, path);
2087  } else {
2088    FileDescriptor stdin_dup;
2089    int error = file_open_stdin(&stdin_dup);
2090    if (error) {
2091      return false;
2092    }
2093
2094    StringBuilder sb = KV_INITIAL_VALUE;
2095    kv_resize(sb, 64);
2096    // Read all input from stdin, unless interrupted (ctrl-c).
2097    while (true) {
2098      if (got_int) {  // User canceled.
2099        file_close(&stdin_dup, false);
2100        kv_destroy(sb);
2101        return false;
2102      }
2103      ptrdiff_t read_size = file_read(&stdin_dup, IObuff, 64);
2104      if (read_size < 0) {  // Error.
2105        file_close(&stdin_dup, false);
2106        kv_destroy(sb);
2107        return false;
2108      }
2109      if (read_size > 0) {
2110        kv_concat_len(sb, IObuff, (size_t)read_size);
2111      }
2112      if (read_size < 64) {  // EOF.
2113        break;
2114      }
2115    }
2116    kv_push(sb, NUL);
2117    file_close(&stdin_dup, false);
2118
2119    lua_getglobal(lstate, "loadstring");
2120    lua_pushstring(lstate, sb.items);
2121    kv_destroy(sb);
2122  }
2123
2124  if (nlua_pcall(lstate, 1, 2)) {
2125    nlua_error(lstate, _("E5111: Lua: %.*s"));
2126    return false;
2127  }
2128
2129  // loadstring() returns either:
2130  //  1. nil, error
2131  //  2. chunk, nil
2132
2133  if (lua_isnil(lstate, -2)) {
2134    // 1
2135    nlua_error(lstate, _("E5112: Lua chunk: %.*s"));
2136    assert(lua_isnil(lstate, -1));
2137    lua_pop(lstate, 1);
2138    return false;
2139  }
2140
2141  // 2
2142  assert(lua_isnil(lstate, -1));
2143  lua_pop(lstate, 1);
2144
2145  if (nlua_pcall(lstate, 0, 0)) {
2146    nlua_error(lstate, _("E5113: Lua chunk: %.*s"));
2147    return false;
2148  }
2149
2150  return 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{
2159  lua_State *const lstate = global_lstate;
2160  int status = FAIL;
2161
2162  // [ vim ]
2163  lua_getglobal(lstate, "vim");
2164
2165  // [ vim, vim._expand_pat ]
2166  lua_getfield(lstate, -1, "_expand_pat");
2167  luaL_checktype(lstate, -1, LUA_TFUNCTION);
2168
2169  // [ vim, vim._expand_pat, pat ]
2170  const char *pat = xp->xp_pattern;
2171  assert(xp->xp_line + xp->xp_col >= pat);
2172  ptrdiff_t patlen = xp->xp_line + xp->xp_col - pat;
2173  lua_pushlstring(lstate, pat, (size_t)patlen);
2174
2175  if (nlua_pcall(lstate, 1, 2) != 0) {
2176    nlua_error(lstate, _("vim._expand_pat: %.*s"));
2177    return;
2178  }
2179
2180  Error err = ERROR_INIT;
2181
2182  Arena arena = ARENA_EMPTY;
2183  ptrdiff_t prefix_len = nlua_pop_Integer(lstate, &arena, &err);
2184  if (ERROR_SET(&err) || prefix_len > patlen) {
2185    goto cleanup;
2186  }
2187
2188  Array completions = nlua_pop_Array(lstate, &arena, &err);
2189  if (ERROR_SET(&err)) {
2190    goto cleanup_array;
2191  }
2192
2193  ga_clear(&expand_result_array);
2194  ga_init(&expand_result_array, (int)sizeof(char *), 80);
2195
2196  for (size_t i = 0; i < completions.size; i++) {
2197    Object v = completions.items[i];
2198    if (v.type != kObjectTypeString) {
2199      goto cleanup_array;
2200    }
2201    GA_APPEND(char *, &expand_result_array, string_to_cstr(v.data.string));
2202  }
2203
2204  xp->xp_pattern += prefix_len;
2205  status = OK;
2206
2207cleanup_array:
2208  arena_mem_free(arena_finish(&arena));
2209
2210cleanup:
2211  if (status == FAIL) {
2212    ga_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;
2220  expand_result_array = (garray_T)GA_EMPTY_INIT_VALUE;
2221  return *num_results > 0;
2222}
2223
2224static int nlua_is_thread(lua_State *lstate)
2225{
2226  lua_getfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
2227
2228  return 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{
2234  if (arg->v_type == VAR_DICT) {
2235    return arg->vval.v_dict->lua_table_ref != LUA_NOREF;
2236  } else if (arg->v_type == VAR_LIST) {
2237    return arg->vval.v_list->lua_table_ref != LUA_NOREF;
2238  } else {
2239    return false;
2240  }
2241}
2242
2243char *nlua_register_table_as_callable(const typval_T *const arg)
2244{
2245  LuaRef table_ref = LUA_NOREF;
2246  if (arg->v_type == VAR_DICT) {
2247    table_ref = arg->vval.v_dict->lua_table_ref;
2248  } else if (arg->v_type == VAR_LIST) {
2249    table_ref = arg->vval.v_list->lua_table_ref;
2250  }
2251
2252  if (table_ref == LUA_NOREF) {
2253    return NULL;
2254  }
2255
2256  lua_State *const lstate = global_lstate;
2257
2258#ifndef NDEBUG
2259  int top = lua_gettop(lstate);
2260#endif
2261
2262  nlua_pushref(lstate, table_ref);  // [table]
2263  if (!lua_getmetatable(lstate, -1)) {
2264    lua_pop(lstate, 1);
2265    assert(top == lua_gettop(lstate));
2266    return NULL;
2267  }  // [table, mt]
2268
2269  lua_getfield(lstate, -1, "__call");  // [table, mt, mt.__call]
2270  if (!lua_isfunction(lstate, -1)) {
2271    lua_pop(lstate, 3);
2272    assert(top == lua_gettop(lstate));
2273    return NULL;
2274  }
2275  lua_pop(lstate, 2);  // [table]
2276
2277  LuaRef func = nlua_ref_global(lstate, -1);
2278
2279  char *name = register_luafunc(func);
2280
2281  lua_pop(lstate, 1);  // []
2282  assert(top == lua_gettop(lstate));
2283
2284  return name;
2285}
2286
2287/// @return true to discard the key
2288bool nlua_exec_on_key(int c, char *typed_buf)
2289{
2290  static bool recursive = false;
2291
2292  if (recursive) {
2293    return false;
2294  }
2295  recursive = true;
2296
2297  char buf[MB_MAXBYTES * 3 + 4];
2298  size_t buf_len = special_to_buf(c, mod_mask, false, buf);
2299  vim_unescape_ks(typed_buf);
2300
2301  lua_State *const lstate = global_lstate;
2302
2303#ifndef NDEBUG
2304  int top = lua_gettop(lstate);
2305#endif
2306
2307  // [ vim ]
2308  lua_getglobal(lstate, "vim");
2309
2310  // [ vim, vim._on_key ]
2311  lua_getfield(lstate, -1, "_on_key");
2312  luaL_checktype(lstate, -1, LUA_TFUNCTION);
2313
2314  // [ vim, vim._on_key, buf ]
2315  lua_pushlstring(lstate, buf, buf_len);
2316
2317  // [ vim, vim._on_key, buf, typed_buf ]
2318  lua_pushstring(lstate, typed_buf);
2319
2320  int save_got_int = got_int;
2321  got_int = false;  // avoid interrupts when the key typed is Ctrl-C
2322  bool discard = false;
2323  // Do not use nlua_pcall here to avoid duplicate stack trace information
2324  if (lua_pcall(lstate, 2, 1, 0)) {
2325    nlua_error(lstate, _("vim.on_key() callbacks: %.*s"));
2326  } else {
2327    if (lua_isboolean(lstate, -1)) {
2328      discard = lua_toboolean(lstate, -1);
2329    }
2330    lua_pop(lstate, 1);
2331  }
2332  got_int |= save_got_int;
2333
2334  // [ vim ]
2335  lua_pop(lstate, 1);
2336
2337#ifndef NDEBUG
2338  // [ ]
2339  assert(top == lua_gettop(lstate));
2340#endif
2341
2342  recursive = false;
2343  return 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{
2350  if (!script_is_lua(current->sc_sid)) {
2351    return;
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.
2357  current->sc_lnum = 0;
2358
2359  if (p_verbose <= 0) {
2360    return;
2361  }
2362  lua_State *const lstate = active_lstate;
2363  lua_Debug *info = (lua_Debug *)xmalloc(sizeof(lua_Debug));
2364
2365  for (int level = 1; true; level++) {
2366    if (lua_getstack(lstate, level, info) != 1) {
2367      goto cleanup;
2368    }
2369    if (lua_getinfo(lstate, "nSl", info) == 0) {
2370      goto cleanup;
2371    }
2372    if (info->what[0] == 'C' || info->source[0] != '@') {
2373      continue;
2374    }
2375    break;
2376  }
2377  char *source_path = fix_fname(info->source + 1);
2378  int sid = find_script_by_name(source_path);
2379  if (sid > 0) {
2380    xfree(source_path);
2381  } else {
2382    scriptitem_T *si = new_script_item(source_path, &sid);
2383    si->sn_lua = true;
2384  }
2385  current->sc_sid = sid;
2386  current->sc_seq = -1;
2387  current->sc_lnum = info->currentline;
2388
2389cleanup:
2390  xfree(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{
2396  lua_State *const lstate = global_lstate;
2397
2398  nlua_pushref(lstate, preview ? cmd->uc_preview_luaref : cmd->uc_luaref);
2399
2400  lua_newtable(lstate);
2401  nlua_push_eap(lstate, eap, &cmdmod);
2402
2403  lua_pushstring(lstate, cmd->uc_name);
2404  lua_setfield(lstate, -2, "name");
2405
2406  // Override count with uc_def fallback for user commands.
2407  if (eap->addr_count == 0) {
2408    lua_pushinteger(lstate, cmd->uc_def);
2409    lua_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`.
2414  if (cmd->uc_argt & EX_NOSPC) {
2415    lua_createtable(lstate, 1, 0);
2416    if ((cmd->uc_argt & EX_NEEDARG) || *eap->arg != NUL) {
2417      lua_pushstring(lstate, eap->arg);
2418      lua_rawseti(lstate, -2, 1);
2419    }
2420    lua_setfield(lstate, -2, "fargs");
2421  }
2422
2423  char nargs[2];
2424  if (cmd->uc_argt & EX_EXTRA) {
2425    if (cmd->uc_argt & EX_NOSPC) {
2426      if (cmd->uc_argt & EX_ARGSPACE) {
2427        nargs[0] = '_';
2428      } else if (cmd->uc_argt & EX_NEEDARG) {
2429        nargs[0] = '1';
2430      } else {
2431        nargs[0] = '?';
2432      }
2433    } else if (cmd->uc_argt & EX_NEEDARG) {
2434      nargs[0] = '+';
2435    } else {
2436      nargs[0] = '*';
2437    }
2438  } else {
2439    nargs[0] = '0';
2440  }
2441  nargs[1] = NUL;
2442  lua_pushstring(lstate, nargs);
2443  lua_setfield(lstate, -2, "nargs");
2444
2445  if (preview) {
2446    lua_pushinteger(lstate, cmdpreview_get_ns());
2447
2448    handle_T cmdpreview_bufnr = cmdpreview_get_bufnr();
2449    if (cmdpreview_bufnr != 0) {
2450      lua_pushinteger(lstate, cmdpreview_bufnr);
2451    } else {
2452      lua_pushnil(lstate);
2453    }
2454  }
2455
2456  if (nlua_pcall(lstate, preview ? 3 : 1, preview ? 1 : 0)) {
2457    nlua_error(lstate, _("Lua :command callback: %.*s"));
2458    return 0;
2459  }
2460
2461  int retv = 0;
2462
2463  if (preview) {
2464    if (lua_isnumber(lstate, -1) && (retv = (int)lua_tointeger(lstate, -1)) >= 0 && retv <= 2) {
2465      lua_pop(lstate, 1);
2466    } else {
2467      retv = 0;
2468    }
2469  }
2470
2471  return 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{
2479  lua_State *const lstate = global_lstate;
2480
2481  if (!lua_checkstack(lstate, 1)) {
2482    goto plain;
2483  }
2484  nlua_pushref(lstate, ref);
2485  if (!lua_isfunction(lstate, -1)) {
2486    lua_pop(lstate, 1);
2487    goto plain;
2488  }
2489
2490  lua_Debug ar;
2491  if (lua_getinfo(lstate, ">S", &ar) && *ar.source == '@' && ar.linedefined >= 0) {
2492    char *src = home_replace_save(NULL, ar.source + 1);
2493    String str = show_ref ? arena_printf(arena, "<Lua %d: %s:%d>", ref, src, ar.linedefined)
2494                          : arena_printf(arena, "<Lua %s:%d>", src, ar.linedefined);
2495    xfree(src);
2496    return str.data;
2497  }
2498
2499plain: {}
2500  return 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{
2506  lua_State *const L = global_lstate;
2507  assert(L);
2508
2509  lua_getglobal(L, "require");
2510  lua_pushstring(L, "vim._core.defaults");
2511  if (nlua_pcall(L, 1, 0)) {
2512    fprintf(stderr, "%s\n", lua_tostring(L, -1));
2513  }
2514}
2515
2516/// check lua function exist
2517bool nlua_func_exists(const char *lua_funcname)
2518{
2519  MAXSIZE_TEMP_ARRAY(args, 1);
2520  size_t length = strlen(lua_funcname) + 8;
2521  char *str = xmalloc(length);
2522  vim_snprintf(str, length, "return %s", lua_funcname);
2523  ADD_C(args, CSTR_AS_OBJ(str));
2524  Error err = ERROR_INIT;
2525  Object result = NLUA_EXEC_STATIC("return type(loadstring(...)()) == 'function'", args,
2526                                   kRetNilBool, NULL, &err);
2527  xfree(str);
2528
2529  api_clear_error(&err);
2530  return LUARET_TRUTHY(result);
2531}