robin/laufey

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

Justin M. Keyesfix(logging): vimscript API calls #41253abc271d8f3

master
31.9 KiB1066 linesraw
1---@diagnostic disable: no-unknown
2-- Generates C code to bridge API <=> Lua.
3
4-- to obtain how the script is invoked, look in build/build.ninja and grep for
5-- "gen_api_dispatch.lua"
6local hashy = require 'gen.hashy'
7local keyset = require('gen.keyset')
8local c_grammar = require('gen.c_grammar')
9
10-- output h file with generated dispatch functions (dispatch_wrappers.generated.h)
11local dispatch_outputf = arg[1]
12-- output file with exported functions metadata
13local exported_funcs_metadata_outputf = arg[2]
14-- output mpack file with raw metadata, for use by gen_eval.lua (funcs_metadata.mpack)
15local eval_funcs_metadata_outputf = arg[3]
16local lua_c_bindings_outputf = arg[4] -- lua_api_c_bindings.generated.c
17local keysets_outputf = arg[5] -- keysets_defs.generated.h
18local dispatch_deprecated_inputf = arg[6]
19local pre_args = 6
20assert(#arg >= 6)
21
22local function real_type(type, exported)
23  local ptype = c_grammar.typed_container:match(type)
24  if ptype then
25    local container = ptype[1]
26    if container == 'Union' then
27      return 'Object'
28    elseif container == 'Tuple' then
29      return 'Array'
30    elseif container == 'ArrayOf' then
31      if exported then
32        local elem = real_type(ptype[2], true)
33        if ptype[3] then
34          return ('ArrayOf(%s, %s)'):format(elem, ptype[3])
35        end
36        return ('ArrayOf(%s)'):format(elem)
37      end
38      return 'Array'
39    elseif container == 'DictOf' or container == 'DictAs' then
40      return 'Dict'
41    elseif container == 'LuaRefOf' then
42      return 'LuaRef'
43    elseif container == 'Enum' then
44      return 'String'
45    elseif container == 'Dict' then
46      if exported then
47        return 'Dict'
48      end
49      -- internal type, used for keysets
50      return 'KeyDict_' .. ptype[2]
51    end
52  end
53  return type
54end
55
56--- @class gen_api_dispatch.Function : nvim.c_grammar.Proto
57--- @field method boolean
58--- @field receives_array_args? true
59--- @field receives_channel_id? true
60--- @field can_fail? true
61--- @field has_lua_imp? true
62--- @field receives_arena? true
63--- @field opts_idx? integer Index of the `opts` param: starts optional params. #31903
64--- @field impl_name? string
65--- @field remote? boolean
66--- @field lua? boolean
67--- @field eval? boolean
68--- @field handler_id? integer
69
70--- @type gen_api_dispatch.Function[]
71local functions = {}
72
73--- Names of all headers relative to the source root (for inclusion in the
74--- generated file)
75--- @type string[]
76local headers = {}
77
78--- Set of function names, used to detect duplicates
79--- @type table<string, true>
80local function_names = {}
81
82local startswith = vim.startswith
83
84--- @param fn gen_api_dispatch.Function
85local function add_function(fn)
86  local public = startswith(fn.name, 'nvim_') or fn.deprecated_since
87  if public and not fn.noexport then
88    functions[#functions + 1] = fn
89    function_names[fn.name] = true
90    if
91      #fn.parameters >= 2
92      and fn.parameters[2][1] == 'Array'
93      and fn.parameters[2][2] == 'uidata'
94    then
95      -- function receives the "args" as a parameter
96      fn.receives_array_args = true
97      -- remove the args parameter
98      table.remove(fn.parameters, 2)
99    end
100    if #fn.parameters ~= 0 and fn.parameters[1][2] == 'channel_id' then
101      -- this function should receive the channel id
102      fn.receives_channel_id = true
103      -- remove the parameter since it won't be passed by the api client
104      table.remove(fn.parameters, 1)
105    end
106    if #fn.parameters ~= 0 and fn.parameters[#fn.parameters][1] == 'error' then
107      -- function can fail if the last parameter type is 'Error'
108      fn.can_fail = true
109      -- remove the error parameter, msgpack has it's own special field
110      -- for specifying errors
111      fn.parameters[#fn.parameters] = nil
112    end
113    if #fn.parameters ~= 0 and fn.parameters[#fn.parameters][1] == 'lstate' then
114      fn.has_lua_imp = true
115      fn.parameters[#fn.parameters] = nil
116    end
117    if #fn.parameters ~= 0 and fn.parameters[#fn.parameters][1] == 'arena' then
118      fn.receives_arena = true
119      fn.parameters[#fn.parameters] = nil
120    end
121    -- `opts` (a KeyDict) and every parameter following it are optional: clients may omit them.
122    fn.opts_idx = c_grammar.opts_index(fn.parameters)
123    -- Omitted optional param is zero-initialized, which assumes Dict/Array.
124    if fn.opts_idx then
125      for k = fn.opts_idx + 1, #fn.parameters do
126        local rt = real_type(fn.parameters[k][1])
127        if not (rt == 'Dict' or rt == 'Dictionary' or rt == 'Array' or rt:match('^KeyDict_')) then
128          local msg = '%s: optional param "%s" has type "%s" but (currently) we assume Dict/Array'
129          error(msg:format(fn.name, fn.parameters[k][2], fn.parameters[k][1]))
130        end
131      end
132    end
133  end
134end
135
136--- @class gen_api_dispatch.Keyset
137--- @field name string
138--- @field keys string[]
139--- @field c_names table<string, string>
140--- @field types table<string, string>
141--- @field has_optional boolean
142
143--- @type gen_api_dispatch.Keyset[]
144local keysets = {}
145
146--- @param val nvim.c_grammar.Keyset
147local function add_keyset(val)
148  local keys = {} --- @type string[]
149  local types = {} --- @type table<string, string>
150  local c_names = {} --- @type table<string, string>
151  local is_set_name = 'is_set__' .. val.keyset_name .. '_'
152  local has_optional = false
153  for i, field in ipairs(val.fields) do
154    local dict_key = field.dict_key or field.name
155    if field.type ~= 'Object' then
156      types[dict_key] = field.type
157    end
158    if field.name ~= is_set_name and field.type ~= 'OptionalKeys' then
159      table.insert(keys, dict_key)
160      if dict_key ~= field.name then
161        c_names[dict_key] = field.name
162      end
163    else
164      if i > 1 then
165        error("'is_set__{type}_' must be first if present")
166      elseif field.name ~= is_set_name then
167        error(val.keyset_name .. ': name of first key should be ' .. is_set_name)
168      elseif field.type ~= 'OptionalKeys' then
169        error("'" .. is_set_name .. "' must have type 'OptionalKeys'")
170      end
171      has_optional = true
172    end
173  end
174  keysets[#keysets + 1] = {
175    name = val.keyset_name,
176    keys = keys,
177    c_names = c_names,
178    types = types,
179    has_optional = has_optional,
180  }
181end
182
183-- read each input file, parse and append to the api metadata
184for i = pre_args + 1, #arg do
185  local full_path = arg[i]
186  local parts = {} --- @type string[]
187  for part in full_path:gmatch('[^/\\]+') do
188    parts[#parts + 1] = part
189  end
190  headers[#headers + 1] = parts[#parts - 1] .. '/' .. parts[#parts]
191
192  local input = assert(io.open(full_path, 'rb'))
193
194  --- @type string
195  local text = input:read('*all')
196  for _, val in ipairs(c_grammar.grammar:match(text)) do
197    if val.keyset_name then
198      --- @cast val nvim.c_grammar.Keyset
199      add_keyset(val)
200    elseif val.name then
201      --- @cast val gen_api_dispatch.Function
202      add_function(val)
203    end
204  end
205
206  input:close()
207end
208
209--- @generic T: table
210--- @param orig T
211--- @return T
212local function shallowcopy(orig)
213  local copy = {}
214  for orig_key, orig_value in pairs(orig) do
215    copy[orig_key] = orig_value
216  end
217  return copy
218end
219
220--- Export functions under older deprecated names.
221--- These will be removed eventually.
222--- @type table<string, string>
223local deprecated_aliases = loadfile(dispatch_deprecated_inputf)()
224
225for _, f in ipairs(shallowcopy(functions)) do
226  local ismethod = false
227  if startswith(f.name, 'nvim_') then
228    if startswith(f.name, 'nvim__') or f.name == 'nvim_error_event' then
229      f.since = -1
230    elseif f.since == nil then
231      print('Function ' .. f.name .. ' lacks since field.\n')
232      os.exit(1)
233    end
234    f.since = tonumber(f.since)
235    if f.deprecated_since ~= nil then
236      f.deprecated_since = tonumber(f.deprecated_since)
237    end
238
239    if startswith(f.name, 'nvim_buf_') then
240      ismethod = true
241    elseif startswith(f.name, 'nvim_win_') then
242      ismethod = true
243    elseif startswith(f.name, 'nvim_tabpage_') then
244      ismethod = true
245    end
246    f.remote = f.remote_only or not f.lua_only
247    f.lua = f.lua_only or not f.remote_only
248    f.eval = (not f.lua_only) and not f.remote_only
249  else
250    f.deprecated_since = tonumber(f.deprecated_since)
251    assert(f.deprecated_since == 1)
252    f.remote = true
253    f.since = 0
254  end
255  f.method = ismethod
256  local newname = deprecated_aliases[f.name]
257  if newname ~= nil then
258    if function_names[newname] then
259      -- duplicate
260      print(
261        'Function '
262          .. f.name
263          .. ' has deprecated alias\n'
264          .. newname
265          .. ' which has a separate implementation.\n'
266          .. 'Remove it from src/nvim/api/dispatch_deprecated.lua'
267      )
268      os.exit(1)
269    end
270    local newf = shallowcopy(f)
271    newf.name = newname
272    if newname == 'ui_try_resize' then
273      -- The return type was incorrectly set to Object in 0.1.5.
274      -- Keep it that way for clients that rely on this.
275      newf.return_type = 'Object'
276    end
277    newf.impl_name = f.name
278    newf.lua = false
279    newf.eval = false
280    newf.since = 0
281    newf.deprecated_since = 1
282    functions[#functions + 1] = newf
283  end
284end
285
286--- don't expose internal attributes like "impl_name" in public metadata
287--- @class gen_api_dispatch.Function.Exported
288--- @field name string
289--- @field parameters [string, string, boolean][] each param is `[ type, name, optional ]`
290--- @field return_type string
291--- @field method boolean
292--- @field since integer
293--- @field deprecated_since integer
294
295--- @type gen_api_dispatch.Function.Exported[]
296local exported_functions = {}
297
298for _, f in ipairs(functions) do
299  if not (startswith(f.name, 'nvim__') or f.name == 'nvim_error_event' or f.name == 'redraw') then
300    --- @type gen_api_dispatch.Function.Exported
301    local f_exported = {
302      name = f.name,
303      method = f.method,
304      since = f.since,
305      deprecated_since = f.deprecated_since,
306      parameters = {},
307      return_type = real_type(f.return_type, true),
308    }
309    for i, param in ipairs(f.parameters) do
310      -- `opts` and every param after it are optional.
311      local optional = f.opts_idx ~= nil and i >= f.opts_idx
312      f_exported.parameters[i] = { real_type(param[1], true), param[2], optional }
313    end
314    exported_functions[#exported_functions + 1] = f_exported
315  end
316end
317
318local metadata_output = assert(io.open(exported_funcs_metadata_outputf, 'wb'))
319metadata_output:write(vim.mpack.encode(exported_functions))
320metadata_output:close()
321
322-- start building the dispatch wrapper output
323local output = assert(io.open(dispatch_outputf, 'wb'))
324
325-- ===========================================================================
326-- NEW API FILES MUST GO HERE.
327--
328--  When creating a new API file, you must include it here,
329--  so that the dispatcher can find the C functions that you are creating!
330-- ===========================================================================
331output:write([[
332#include "nvim/errors.h"
333#include "nvim/ex_docmd.h"
334#include "nvim/ex_getln.h"
335#include "nvim/globals.h"
336#include "nvim/log.h"
337#include "nvim/map_defs.h"
338
339#include "nvim/api/autocmd.h"
340#include "nvim/api/buffer.h"
341#include "nvim/api/command.h"
342#include "nvim/api/deprecated.h"
343#include "nvim/api/events.h"
344#include "nvim/api/extmark.h"
345#include "nvim/api/options.h"
346#include "nvim/api/tabpage.h"
347#include "nvim/api/ui.h"
348#include "nvim/api/vim.h"
349#include "nvim/api/vimscript.h"
350#include "nvim/api/win_config.h"
351#include "nvim/api/window.h"
352#include "nvim/ui_client.h"
353
354]])
355
356local keysets_defs = assert(io.open(keysets_outputf, 'wb'))
357
358keysets_defs:write('// IWYU pragma: private, include "nvim/api/private/dispatch.h"\n\n')
359
360local function typename(type)
361  if type == 'HLGroupID' then
362    return 'kObjectTypeInteger'
363  elseif not type or startswith(type, 'Union') then
364    return 'kObjectTypeNil'
365  elseif type == 'StringArray' then
366    return 'kUnpackTypeStringArray'
367  end
368  return 'kObjectType' .. real_type(type)
369end
370
371for _, k in ipairs(keysets) do
372  local order, hashfun = keyset.hash(k.name, k.keys)
373  keysets_defs:write('extern KeySetLink ' .. k.name .. '_table[' .. (1 + #order) .. '];\n')
374
375  local entry = {} --- @type table<string, gen.keyset.entry>
376  for i, key in ipairs(order) do
377    -- Only keysets with optional keys carry a per-key HAS_KEY index (and its `KEYSET_OPTIDX` define).
378    local ind = -1
379    if k.has_optional then
380      ind = i
381      keysets_defs:write('#define KEYSET_OPTIDX_' .. k.name .. '__' .. key .. ' ' .. ind .. '\n')
382    end
383    entry[key] = {
384      field = k.c_names[key] or key,
385      type = typename(k.types[key]),
386      opt_index = ind,
387      is_hlgroup = k.types[key] == 'HLGroupID',
388    }
389  end
390
391  keyset.emit(function(s)
392    output:write(s .. '\n')
393  end, {
394    name = k.name,
395    get_field = 'KeyDict_' .. k.name .. '_get_field',
396    struct = 'KeyDict_' .. k.name,
397    order = order,
398    hashfun = hashfun,
399    entry = entry,
400    static = false,
401  })
402  output:write('\n')
403end
404
405keysets_defs:close()
406
407local function attr_name(rt)
408  if rt == 'Float' then
409    return 'floating'
410  else
411    return rt:lower()
412  end
413end
414
415-- start the handler functions. Visit each function metadata to build the
416-- handler function with code generated for validating arguments and calling to
417-- the real API.
418for i = 1, #functions do
419  local fn = functions[i]
420  if fn.impl_name == nil and fn.remote then
421    local args = {} --- @type string[]
422
423    output:write(
424      'Object handle_' .. fn.name .. '(uint64_t channel_id, Array args, Arena* arena, Error *error)'
425    )
426    output:write('\n{')
427    output:write('\n#ifdef NVIM_LOG_DEBUG')
428    -- Log only internal calls: an RPC caller is logged by log_request()/log_notify().
429    -- An internal call is always Vimscript (api_wrapper()); vim.api binds to nvim_foo() directly.
430    output:write(
431      ('\n  if (is_internal_call(channel_id)) {\n    DLOG("API: vim -> %s");\n  }'):format(fn.name)
432    )
433    output:write('\n#endif')
434    output:write('\n  Object ret = NIL;')
435    -- Declare/initialize variables that will hold converted arguments
436    for j = 1, #fn.parameters do
437      local param = fn.parameters[j]
438      local rt = real_type(param[1])
439      local converted = 'arg_' .. j
440      -- Optional params (`opts` + rest) are currently assumed to be Dict/Array types (enforced in add_function).
441      if fn.opts_idx and j >= fn.opts_idx then
442        output:write('\n  ' .. rt .. ' ' .. converted .. ' = { 0 };')
443      else
444        output:write('\n  ' .. rt .. ' ' .. converted .. ';')
445      end
446    end
447    output:write('\n')
448    if not fn.receives_array_args then
449      -- `opts` and following params are optional: accept minargs..maxargs; else require maxargs.
450      local maxargs = #fn.parameters
451      local minargs = fn.opts_idx and fn.opts_idx - 1 or maxargs
452      local cond, expect
453      if minargs == maxargs then
454        cond, expect = 'args.size != ' .. maxargs, maxargs
455      elseif minargs > 0 then
456        cond, expect =
457          'args.size < ' .. minargs .. ' || args.size > ' .. maxargs, minargs .. ' to ' .. maxargs
458      else
459        cond, expect = 'args.size > ' .. maxargs, 'at most ' .. maxargs
460      end
461      output:write('\n  if (' .. cond .. ') {')
462      output:write('\n    api_set_error(error, kErrorTypeException, \
463        "Wrong number of arguments: expecting ' .. expect .. ' but got %zu", args.size);')
464      output:write('\n    goto cleanup;')
465      output:write('\n  }\n')
466    end
467
468    -- Validation/conversion for each argument
469    for j = 1, #fn.parameters do
470      local converted, param
471      param = fn.parameters[j]
472      converted = 'arg_' .. j
473      local rt = real_type(param[1])
474      -- `opts` + rest are optional: ensure omitted arg keeps its zero-initialized default.
475      local optional = fn.opts_idx and j >= fn.opts_idx
476      if optional then
477        output:write('\n  if (args.size >= ' .. j .. ') {')
478      end
479      if rt == 'Object' then
480        output:write('\n  ' .. converted .. ' = args.items[' .. (j - 1) .. '];\n')
481      elseif rt:match('^KeyDict_') then
482        converted = '&' .. converted
483        output:write('\n  if (args.items[' .. (j - 1) .. '].type == kObjectTypeDict) {') --luacheck: ignore 631
484        output:write('\n    memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));') -- TODO: neeeee
485        output:write(
486          '\n    if (!api_dict_to_keydict('
487            .. converted
488            .. ', '
489            .. rt
490            .. '_get_field, args.items['
491            .. (j - 1)
492            .. '].data.dict, error)) {'
493        )
494        output:write('\n      goto cleanup;')
495        output:write('\n    }')
496        output:write(
497          '\n  } else if (args.items['
498            .. (j - 1)
499            .. '].type == kObjectTypeArray && args.items['
500            .. (j - 1)
501            .. '].data.array.size == 0) {'
502        ) --luacheck: ignore 631
503        output:write('\n    memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));')
504
505        output:write('\n  } else {')
506        output:write(
507          '\n    api_set_error(error, kErrorTypeException, \
508          "Wrong type for argument '
509            .. j
510            .. ' when calling '
511            .. fn.name
512            .. ', expecting '
513            .. param[1]
514            .. '");'
515        )
516        output:write('\n    goto cleanup;')
517        output:write('\n  }\n')
518      else
519        if rt:match('^Buffer$') or rt:match('^Window$') or rt:match('^Tabpage$') then
520          -- Buffer, Window, and Tabpage have a specific type, but are stored in integer
521          output:write(
522            '\n  if (args.items['
523              .. (j - 1)
524              .. '].type == kObjectType'
525              .. rt
526              .. ' && args.items['
527              .. (j - 1)
528              .. '].data.integer >= 0) {'
529          )
530          output:write(
531            '\n    ' .. converted .. ' = (handle_T)args.items[' .. (j - 1) .. '].data.integer;'
532          )
533        else
534          output:write('\n  if (args.items[' .. (j - 1) .. '].type == kObjectType' .. rt .. ') {')
535          output:write(
536            '\n    '
537              .. converted
538              .. ' = args.items['
539              .. (j - 1)
540              .. '].data.'
541              .. attr_name(rt)
542              .. ';'
543          )
544        end
545        if
546          rt:match('^Buffer$')
547          or rt:match('^Window$')
548          or rt:match('^Tabpage$')
549          or rt:match('^Boolean$')
550        then
551          -- accept nonnegative integers for Booleans, Buffers, Windows and Tabpages
552          output:write(
553            '\n  } else if (args.items['
554              .. (j - 1)
555              .. '].type == kObjectTypeInteger && args.items['
556              .. (j - 1)
557              .. '].data.integer >= 0) {'
558          )
559          output:write(
560            '\n    ' .. converted .. ' = (handle_T)args.items[' .. (j - 1) .. '].data.integer;'
561          )
562        end
563        if rt:match('^Float$') then
564          -- accept integers for Floats
565          output:write('\n  } else if (args.items[' .. (j - 1) .. '].type == kObjectTypeInteger) {')
566          output:write(
567            '\n    ' .. converted .. ' = (Float)args.items[' .. (j - 1) .. '].data.integer;'
568          )
569        end
570        -- accept empty lua tables as empty dictionaries
571        if rt:match('^Dict') then
572          output:write(
573            '\n  } else if (args.items['
574              .. (j - 1)
575              .. '].type == kObjectTypeArray && args.items['
576              .. (j - 1)
577              .. '].data.array.size == 0) {'
578          ) --luacheck: ignore 631
579          output:write('\n    ' .. converted .. ' = (Dict)ARRAY_DICT_INIT;')
580        end
581        output:write('\n  } else {')
582        output:write(
583          '\n    api_set_error(error, kErrorTypeException, \
584          "Wrong type for argument '
585            .. j
586            .. ' when calling '
587            .. fn.name
588            .. ', expecting '
589            .. param[1]
590            .. '");'
591        )
592        output:write('\n    goto cleanup;')
593        output:write('\n  }\n')
594      end
595      if optional then
596        output:write('\n  }\n')
597      end
598      args[#args + 1] = converted
599    end
600
601    if fn.textlock then
602      output:write('\n  if (text_locked()) {')
603      output:write('\n    api_set_error(error, kErrorTypeException, "%s", get_text_locked_msg());')
604      output:write('\n    goto cleanup;')
605      output:write('\n  }\n')
606    end
607
608    -- function call
609    output:write('\n  ')
610    if fn.return_type ~= 'void' then
611      -- has a return value, prefix the call with a declaration
612      output:write(fn.return_type .. ' rv = ')
613    end
614
615    -- write the function name and the opening parenthesis
616    output:write(fn.name .. '(')
617
618    local call_args = {}
619    if fn.receives_channel_id then
620      table.insert(call_args, 'channel_id')
621    end
622
623    if fn.receives_array_args then
624      table.insert(call_args, 'args')
625    end
626
627    for _, a in ipairs(args) do
628      table.insert(call_args, a)
629    end
630
631    if fn.receives_arena then
632      table.insert(call_args, 'arena')
633    end
634
635    if fn.has_lua_imp then
636      table.insert(call_args, 'NULL')
637    end
638
639    if fn.can_fail then
640      table.insert(call_args, 'error')
641    end
642
643    output:write(table.concat(call_args, ', '))
644    output:write(');\n')
645
646    if fn.can_fail then
647      -- if the function can fail, also pass a pointer to the local error object
648      -- and check for the error
649      output:write('\n  if (ERROR_SET(error)) {')
650      output:write('\n    goto cleanup;')
651      output:write('\n  }\n')
652    end
653
654    local ret_type = real_type(fn.return_type)
655    if ret_type:match('^KeyDict_') then
656      local table = ret_type:sub(9) .. '_table'
657      output:write(
658        '\n  ret = DICT_OBJ(api_keydict_to_dict(&rv, '
659          .. table
660          .. ', ARRAY_SIZE('
661          .. table
662          .. '), arena));'
663      )
664    elseif ret_type ~= 'void' then
665      output:write('\n  ret = ' .. real_type(fn.return_type):upper() .. '_OBJ(rv);')
666    end
667    output:write('\n\ncleanup:')
668
669    output:write('\n  return ret;\n}\n\n')
670  end
671end
672
673--- @type {[string]: gen_api_dispatch.Function, redraw: {impl_name: string, fast: boolean}}
674local remote_fns = {}
675for _, fn in ipairs(functions) do
676  if fn.remote then
677    remote_fns[fn.name] = fn
678  end
679end
680remote_fns.redraw = { impl_name = 'ui_client_redraw', fast = true }
681
682local names = vim.tbl_keys(remote_fns)
683table.sort(names)
684local hashorder, hashfun = hashy.hashy_hash('msgpack_rpc_get_handler_for', names, function(idx)
685  return 'method_handlers[' .. idx .. '].name'
686end)
687
688output:write('const MsgpackRpcRequestHandler method_handlers[] = {\n')
689for n, name in ipairs(hashorder) do
690  local fn = remote_fns[name]
691  fn.handler_id = n - 1
692  output:write(
693    '  { .name = "'
694      .. name
695      .. '", .fn = handle_'
696      .. (fn.impl_name or fn.name)
697      .. ', .fast = '
698      .. tostring(fn.fast)
699      .. ', .ret_alloc = '
700      .. tostring(not not fn.ret_alloc)
701      .. '},\n'
702  )
703end
704output:write('};\n\n')
705output:write(hashfun)
706
707output:close()
708
709--- @cast functions {[integer]: gen_api_dispatch.Function, keysets: gen_api_dispatch.Keyset[]}
710functions.keysets = keysets
711local mpack_output = assert(io.open(eval_funcs_metadata_outputf, 'wb'))
712mpack_output:write(vim.mpack.encode(functions))
713mpack_output:close()
714
715--- @param output_handle file*
716--- @param headers_to_include string[]
717local function include_headers(output_handle, headers_to_include)
718  for i = 1, #headers_to_include do
719    if headers_to_include[i]:sub(-12) ~= '.generated.h' then
720      output_handle:write('\n#include "nvim/' .. headers_to_include[i] .. '"')
721    end
722  end
723end
724
725--- @param str string
726local function write_shifted_output(str, ...)
727  str = str:gsub('\n  ', '\n')
728  str = str:gsub('^  ', '')
729  str = str:gsub(' +$', '')
730  output:write(str:format(...))
731end
732
733-- start building lua output
734output = assert(io.open(lua_c_bindings_outputf, 'wb'))
735
736include_headers(output, headers)
737output:write('\n')
738
739--- @type {binding: string, api:string}[]
740local lua_c_functions = {}
741
742--- Functions which use kRetMultiStack.
743local lua_retstack = { nvim_buf_call = true, nvim_win_call = true }
744
745--- Generates C code to bridge RPC API <=> Lua.
746---
747--- Inspect the result here:
748---    build/src/nvim/auto/api/private/dispatch_wrappers.generated.h
749--- @param fn gen_api_dispatch.Function
750local function process_function(fn)
751  local lua_c_function_name = ('nlua_api_%s'):format(fn.name)
752  write_shifted_output(
753    [[
754
755  static int %s(lua_State *lstate)
756  {
757    Error err = ERROR_INIT;
758    Arena arena = ARENA_EMPTY;
759    char *err_param = 0;
760  ]],
761    lua_c_function_name
762  )
763  do
764    -- `opts` + rest are optional: accept minargs..maxargs; else require maxargs.
765    local maxargs = #fn.parameters
766    local minargs = fn.opts_idx and fn.opts_idx - 1 or maxargs
767    local cond, msg
768    if minargs == maxargs then
769      cond = ('lua_gettop(lstate) != %d'):format(maxargs)
770      msg = ('Expected %d argument%s'):format(maxargs, maxargs == 1 and '' or 's')
771    elseif minargs > 0 then
772      cond = ('lua_gettop(lstate) < %d || lua_gettop(lstate) > %d'):format(minargs, maxargs)
773      msg = ('Expected %d to %d arguments'):format(minargs, maxargs)
774    else
775      cond = ('lua_gettop(lstate) > %d'):format(maxargs)
776      msg = ('Expected at most %d argument%s'):format(maxargs, maxargs == 1 and '' or 's')
777    end
778    write_shifted_output(
779      [[
780    if (%s) {
781      api_set_error(&err, kErrorTypeValidation, "%s");
782      goto exit_0;
783    }
784  ]],
785      cond,
786      msg
787    )
788  end
789  lua_c_functions[#lua_c_functions + 1] = {
790    binding = lua_c_function_name,
791    api = fn.name,
792  }
793
794  if not fn.fast then
795    write_shifted_output(
796      [[
797    if (!nlua_is_deferred_safe()) {
798      return luaL_error(lstate, e_fast_api_disabled, "%s");
799    }
800    ]],
801      fn.name
802    )
803  end
804
805  if fn.textlock then
806    write_shifted_output([[
807    if (text_locked()) {
808      api_set_error(&err, kErrorTypeException, "%%s", get_text_locked_msg());
809      goto exit_0;
810    }
811    ]])
812  end
813
814  local cparams = ''
815  local free_code = {} --- @type string[]
816  for j = #fn.parameters, 1, -1 do
817    local param = fn.parameters[j]
818    local cparam = string.format('arg%u', j)
819    local param_type = real_type(param[1])
820    local extra = param_type == 'Dict' and 'false, ' or ''
821    local arg_free_code = ''
822    if param_type == 'Object' then
823      extra = 'true, '
824      arg_free_code = '  api_luarefs_free_object(' .. cparam .. ');'
825    elseif param[1] == 'DictOf(LuaRef)' then
826      extra = 'true, '
827      arg_free_code = '  api_luarefs_free_dict(' .. cparam .. ');'
828    elseif param[1] == 'LuaRef' then
829      arg_free_code = '  api_free_luaref(' .. cparam .. ');'
830    end
831    local errshift = 0
832    local seterr = ''
833    -- `opts` + rest are optional. Params pop in reverse, so the stack top holds arg `j` exactly
834    -- when `lua_gettop(lstate) == j`; else it was omitted.
835    local optional = fn.opts_idx and j >= fn.opts_idx
836    if param_type:match('^KeyDict_') then
837      if optional then
838        write_shifted_output(
839          [[
840    %s %s = KEYDICT_INIT;
841    if (lua_gettop(lstate) == %d) {
842      nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &arena, &err);
843    ]],
844          param_type,
845          cparam,
846          j,
847          cparam,
848          param_type
849        )
850      else
851        write_shifted_output(
852          [[
853    %s %s = KEYDICT_INIT;
854    nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &arena, &err);
855    ]],
856          param_type,
857          cparam,
858          cparam,
859          param_type
860        )
861      end
862      cparam = '&' .. cparam
863      errshift = 1 -- free incomplete dict on error
864      arg_free_code = '  api_luarefs_free_keydict('
865        .. cparam
866        .. ', '
867        .. param_type:sub(9)
868        .. '_table);'
869    elseif optional then
870      -- Conditionally pop; keep a zero-init `{ 0 }` default when the arg was omitted.
871      write_shifted_output(
872        [[
873    %s %s = { 0 };
874    if (lua_gettop(lstate) == %d) {
875      %s = nlua_pop_%s(lstate, %s&arena, &err);]],
876        param[1],
877        cparam,
878        j,
879        cparam,
880        param_type,
881        extra
882      )
883      seterr = '\n      err_param = "' .. param[2] .. '";'
884    else
885      write_shifted_output(
886        [[
887    const %s %s = nlua_pop_%s(lstate, %s&arena, &err);]],
888        param[1],
889        cparam,
890        param_type,
891        extra
892      )
893      seterr = '\n      err_param = "' .. param[2] .. '";'
894    end
895
896    if optional then
897      write_shifted_output(
898        [[
899      if (ERROR_SET(&err)) {
900        goto exit_%u;
901      }
902    }
903
904    ]],
905        #fn.parameters - j + errshift
906      )
907    else
908      write_shifted_output([[
909
910    if (ERROR_SET(&err)) {]] .. seterr .. [[
911
912      goto exit_%u;
913    }
914
915    ]], #fn.parameters - j + errshift)
916    end
917    free_code[#free_code + 1] = arg_free_code
918    cparams = cparam .. ', ' .. cparams
919  end
920  if fn.receives_channel_id then
921    --- @type string
922    cparams = 'LUA_INTERNAL_CALL, ' .. cparams
923  end
924  if fn.receives_arena then
925    cparams = cparams .. '&arena, '
926  end
927
928  if fn.has_lua_imp then
929    cparams = cparams .. 'lstate, '
930  end
931
932  if fn.can_fail then
933    cparams = cparams .. '&err'
934  else
935    cparams = cparams:gsub(', $', '')
936  end
937
938  write_shifted_output('    ENTER_LUA_ACTIVE_STATE(lstate);\n')
939  if fn.has_lua_imp and not lua_retstack[fn.name] then
940    write_shifted_output('    const int pretop = lua_gettop(lstate); (void)pretop;\n')
941  end
942  local free_at_exit_code = ''
943  for i = 1, #free_code do
944    local rev_i = #free_code - i + 1
945    local code = free_code[rev_i]
946    local cur_is_keydict = real_type(fn.parameters[i][1]):match('^KeyDict_')
947    local prev_is_keydict = i > 1 and real_type(fn.parameters[i - 1][1]):match('^KeyDict_')
948    if not cur_is_keydict and (i == 1 or prev_is_keydict) then
949      free_at_exit_code = free_at_exit_code .. ('\n%s'):format(code)
950    else
951      free_at_exit_code = free_at_exit_code .. ('\nexit_%u:\n%s'):format(rev_i, code)
952    end
953  end
954  local err_throw_code = [[
955
956exit_0:
957  arena_mem_free(arena_finish(&arena));
958  if (ERROR_SET(&err)) {
959    luaL_where(lstate, 1);
960    if (err_param) {
961      lua_pushstring(lstate, "Invalid '");
962      lua_pushstring(lstate, err_param);
963      lua_pushstring(lstate, "': ");
964    }
965    lua_pushstring(lstate, err.msg);
966    api_clear_error(&err);
967    lua_concat(lstate, err_param ? 5 : 2);
968    return lua_error(lstate);
969  }
970]]
971  if fn.return_type ~= 'void' then
972    local return_type = real_type(fn.return_type)
973    local free_retval = ''
974    if fn.ret_alloc then
975      free_retval = '  api_free_' .. return_type:lower() .. '(ret);'
976    end
977    write_shifted_output('    %s ret = %s(%s);\n', fn.return_type, fn.name, cparams)
978
979    local ret_type = real_type(fn.return_type)
980    local ret_mode = (ret_type == 'Object') and '&' or ''
981    if fn.has_lua_imp then
982      -- Most has_lua_imp functions are expected to produce a single retval (e.g.
983      -- nvim_buf_get_lines, but not kRetMultiStack callers such as nvim_buf_call). #39851
984      if not lua_retstack[fn.name] then
985        write_shifted_output(
986          '    assert((ERROR_SET(&err) || lua_gettop(lstate) == pretop + 1) && "has_lua_imp function must push exactly one return value");\n'
987        )
988      end
989      write_shifted_output('    (void)ret;\n')
990    elseif ret_type:match('^KeyDict_') then
991      write_shifted_output('    nlua_push_keydict(lstate, &ret, %s_table);\n', return_type:sub(9))
992    else
993      local special = (fn.since ~= nil and fn.since < 11)
994      write_shifted_output(
995        '    nlua_push_%s(lstate, %sret, %s | kNluaPushFreeRefs);\n',
996        return_type,
997        ret_mode,
998        special and 'kNluaPushSpecial' or '0'
999      )
1000    end
1001
1002    -- NOTE: we currently assume err_throw needs nothing from arena
1003    write_shifted_output(
1004      [[
1005    LEAVE_LUA_ACTIVE_STATE();
1006  %s
1007  %s
1008  %s
1009    return %s;
1010    ]],
1011      free_retval,
1012      free_at_exit_code,
1013      err_throw_code,
1014      (fn.has_lua_imp and 'lua_gettop(lstate)' or '1')
1015    )
1016  else
1017    write_shifted_output(
1018      [[
1019    %s(%s);
1020    LEAVE_LUA_ACTIVE_STATE();
1021  %s
1022  %s
1023    return 0;
1024    ]],
1025      fn.name,
1026      cparams,
1027      free_at_exit_code,
1028      err_throw_code
1029    )
1030  end
1031  write_shifted_output([[
1032  }
1033  ]])
1034end
1035
1036for _, fn in ipairs(functions) do
1037  if fn.lua or fn.name:sub(1, 4) == '_vim' then
1038    process_function(fn)
1039  end
1040end
1041
1042output:write(string.format(
1043  [[
1044void nlua_add_api_functions(lua_State *lstate)
1045{
1046  lua_createtable(lstate, 0, %u);
1047]],
1048  #lua_c_functions
1049))
1050for _, func in ipairs(lua_c_functions) do
1051  output:write(string.format(
1052    [[
1053
1054  lua_pushcfunction(lstate, &%s);
1055  lua_setfield(lstate, -2, "%s");]],
1056    func.binding,
1057    func.api
1058  ))
1059end
1060output:write([[
1061
1062  lua_setfield(lstate, -2, "api");
1063}
1064]])
1065
1066output:close()