robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
abc271d8f3
master
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 ) 23local ptype =c_grammar . typed_container : match ( type ) 24if ptype then 25local container =ptype [ 1 ] 26if container == 'Union' then 27return 'Object' 28elseif container == 'Tuple' then 29return 'Array' 30elseif container == 'ArrayOf' then 31if exported then 32local elem =real_type ( ptype [ 2 ], true ) 33if ptype [ 3 ] then 34return ( 'ArrayOf(%s, %s)' ): format ( elem , ptype [ 3 ]) 35end 36return ( 'ArrayOf(%s)' ): format ( elem ) 37end 38return 'Array' 39elseif container == 'DictOf' or container == 'DictAs' then 40return 'Dict' 41elseif container == 'LuaRefOf' then 42return 'LuaRef' 43elseif container == 'Enum' then 44return 'String' 45elseif container == 'Dict' then 46if exported then 47return 'Dict' 48end 49-- internal type, used for keysets 50return 'KeyDict_' .. ptype [ 2 ] 51end 52end 53return 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 ) 86local public =startswith ( fn . name , 'nvim_' ) or fn . deprecated_since 87if public and not fn . noexport then 88functions [ # functions + 1 ] =fn 89function_names [ fn . name ] =true 90if 91# fn . parameters >= 2 92and fn . parameters [ 2 ][ 1 ] == 'Array' 93and fn . parameters [ 2 ][ 2 ] == 'uidata' 94then 95-- function receives the "args" as a parameter 96fn . receives_array_args =true 97-- remove the args parameter 98table . remove ( fn . parameters , 2 ) 99end 100if # fn . parameters ~= 0 and fn . parameters [ 1 ][ 2 ] == 'channel_id' then 101-- this function should receive the channel id 102fn . receives_channel_id =true 103-- remove the parameter since it won't be passed by the api client 104table . remove ( fn . parameters , 1 ) 105end 106if # fn . parameters ~= 0 and fn . parameters [ # fn . parameters ][ 1 ] == 'error' then 107-- function can fail if the last parameter type is 'Error' 108fn . can_fail =true 109-- remove the error parameter, msgpack has it's own special field 110-- for specifying errors 111fn . parameters [ # fn . parameters ] =nil 112end 113if # fn . parameters ~= 0 and fn . parameters [ # fn . parameters ][ 1 ] == 'lstate' then 114fn . has_lua_imp =true 115fn . parameters [ # fn . parameters ] =nil 116end 117if # fn . parameters ~= 0 and fn . parameters [ # fn . parameters ][ 1 ] == 'arena' then 118fn . receives_arena =true 119fn . parameters [ # fn . parameters ] =nil 120end 121-- `opts` (a KeyDict) and every parameter following it are optional: clients may omit them. 122fn . opts_idx =c_grammar . opts_index ( fn . parameters ) 123-- Omitted optional param is zero-initialized, which assumes Dict/Array. 124if fn . opts_idx then 125for k =fn . opts_idx + 1 , # fn . parameters do 126local rt =real_type ( fn . parameters [ k ][ 1 ]) 127if not ( rt == 'Dict' or rt == 'Dictionary' or rt == 'Array' or rt : match ( '^KeyDict_' )) then 128local msg ='%s: optional param "%s" has type "%s" but (currently) we assume Dict/Array' 129error ( msg : format ( fn . name , fn . parameters [ k ][ 2 ], fn . parameters [ k ][ 1 ])) 130end 131end 132end 133end 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 ) 148local keys ={} --- @type string[] 149local types ={} --- @type table<string, string> 150local c_names ={} --- @type table<string, string> 151local is_set_name ='is_set__' .. val . keyset_name .. '_' 152local has_optional =false 153for i , field in ipairs ( val . fields ) do 154local dict_key =field . dict_key or field . name 155if field . type ~= 'Object' then 156types [ dict_key ] =field . type 157end 158if field . name ~= is_set_name and field . type ~= 'OptionalKeys' then 159table . insert ( keys , dict_key ) 160if dict_key ~= field . name then 161c_names [ dict_key ] =field . name 162end 163else 164if i > 1 then 165error ( "'is_set__{type}_' must be first if present" ) 166elseif field . name ~= is_set_name then 167error ( val . keyset_name .. ': name of first key should be ' .. is_set_name ) 168elseif field . type ~= 'OptionalKeys' then 169error ( "'" .. is_set_name .. "' must have type 'OptionalKeys'" ) 170end 171has_optional =true 172end 173end 174keysets [ # keysets + 1 ] ={ 175name =val . keyset_name , 176keys =keys , 177c_names =c_names , 178types =types , 179has_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 185local full_path =arg [ i ] 186local parts ={} --- @type string[] 187for part in full_path : gmatch ( '[^/\\]+' ) do 188parts [ # parts + 1 ] =part 189end 190headers [ # headers + 1 ] =parts [ # parts - 1 ] .. '/' .. parts [ # parts ] 191 192local input =assert ( io . open ( full_path , 'rb' )) 193 194--- @type string 195local text =input : read ( '*all' ) 196for _ , val in ipairs ( c_grammar . grammar : match ( text )) do 197if val . keyset_name then 198--- @cast val nvim.c_grammar.Keyset 199add_keyset ( val ) 200elseif val . name then 201--- @cast val gen_api_dispatch.Function 202add_function ( val ) 203end 204end 205 206input : close () 207end 208 209--- @generic T: table 210--- @param orig T 211--- @return T 212local function shallowcopy ( orig ) 213local copy ={} 214for orig_key , orig_value in pairs ( orig ) do 215copy [ orig_key ] =orig_value 216end 217return 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 226local ismethod =false 227if startswith ( f . name , 'nvim_' ) then 228if startswith ( f . name , 'nvim__' ) or f . name == 'nvim_error_event' then 229f . since =- 1 230elseif f . since == nil then 231( 'Function ' .. f . name .. ' lacks since field.\n' ) 232os . exit ( 1 ) 233end 234f . since =tonumber ( f . since ) 235if f . deprecated_since ~= nil then 236f . deprecated_since =tonumber ( f . deprecated_since ) 237end 238 239if startswith ( f . name , 'nvim_buf_' ) then 240ismethod =true 241elseif startswith ( f . name , 'nvim_win_' ) then 242ismethod =true 243elseif startswith ( f . name , 'nvim_tabpage_' ) then 244ismethod =true 245end 246f . remote =f . remote_only or not f . lua_only 247f . lua =f . lua_only or not f . remote_only 248f . eval =( not f . lua_only ) and not f . remote_only 249else 250f . deprecated_since =tonumber ( f . deprecated_since ) 251assert ( f . deprecated_since == 1 ) 252f . remote =true 253f . since =0 254end 255f . method =ismethod 256local newname =deprecated_aliases [ f . name ] 257if newname ~= nil then 258if function_names [ newname ] then 259-- duplicate 260( 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) 268os . exit ( 1 ) 269end 270local newf =shallowcopy ( f ) 271newf . name =newname 272if 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. 275newf . return_type ='Object' 276end 277newf . impl_name =f . name 278newf . lua =false 279newf . eval =false 280newf . since =0 281newf . deprecated_since =1 282functions [ # functions + 1 ] =newf 283end 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 299if not ( startswith ( f . name , 'nvim__' ) or f . name == 'nvim_error_event' or f . name == 'redraw' ) then 300--- @type gen_api_dispatch.Function.Exported 301local f_exported ={ 302name =f . name , 303method =f . method , 304since =f . since , 305deprecated_since =f . deprecated_since , 306parameters ={} , 307return_type =real_type ( f . return_type , true ), 308} 309for i , param in ipairs ( f . parameters ) do 310-- `opts` and every param after it are optional. 311local optional =f . opts_idx ~= nil and i >= f . opts_idx 312f_exported . parameters [ i ] ={ real_type ( param [ 1 ], true ), param [ 2 ], optional } 313end 314exported_functions [ # exported_functions + 1 ] =f_exported 315end 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 ) 361if type == 'HLGroupID' then 362return 'kObjectTypeInteger' 363elseif not type or startswith ( type , 'Union' ) then 364return 'kObjectTypeNil' 365elseif type == 'StringArray' then 366return 'kUnpackTypeStringArray' 367end 368return 'kObjectType' .. real_type ( type ) 369end 370 371for _ , k in ipairs ( keysets ) do 372local order , hashfun =keyset . hash ( k . name , k . keys ) 373keysets_defs : write ( 'extern KeySetLink ' .. k . name .. '_table[' .. ( 1 + # order ) .. '];\n' ) 374 375local entry ={} --- @type table<string, gen.keyset.entry> 376for i , key in ipairs ( order ) do 377-- Only keysets with optional keys carry a per-key HAS_KEY index (and its `KEYSET_OPTIDX` define). 378local ind =- 1 379if k . has_optional then 380ind =i 381keysets_defs : write ( '#define KEYSET_OPTIDX_' .. k . name .. '__' .. key .. ' ' .. ind .. '\n' ) 382end 383entry [ key ] ={ 384field =k . c_names [ key ] or key , 385type =typename ( k . types [ key ]), 386opt_index =ind , 387is_hlgroup =k . types [ key ] == 'HLGroupID' , 388} 389end 390 391keyset . emit ( function ( s ) 392output : write ( s .. '\n' ) 393end , { 394name =k . name , 395get_field ='KeyDict_' .. k . name .. '_get_field' , 396struct ='KeyDict_' .. k . name , 397order =order , 398hashfun =hashfun , 399entry =entry , 400static =false , 401} ) 402output : write ( '\n' ) 403end 404 405keysets_defs : close () 406 407local function attr_name ( rt ) 408if rt == 'Float' then 409return 'floating' 410else 411return rt : lower () 412end 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 419local fn =functions [ i ] 420if fn . impl_name == nil and fn . remote then 421local args ={} --- @type string[] 422 423output : write ( 424'Object handle_' .. fn . name .. '(uint64_t channel_id, Array args, Arena* arena, Error *error)' 425) 426output : write ( '\n{' ) 427output : 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. 430output : write ( 431( '\n if (is_internal_call(channel_id)) {\n DLOG("API: vim -> %s");\n }' ): format ( fn . name ) 432) 433output : write ( '\n#endif' ) 434output : write ( '\n Object ret = NIL;' ) 435-- Declare/initialize variables that will hold converted arguments 436for j =1 , # fn . parameters do 437local param =fn . parameters [ j ] 438local rt =real_type ( param [ 1 ]) 439local converted ='arg_' .. j 440-- Optional params (`opts` + rest) are currently assumed to be Dict/Array types (enforced in add_function). 441if fn . opts_idx and j >= fn . opts_idx then 442output : write ( '\n ' .. rt .. ' ' .. converted .. ' = { 0 };' ) 443else 444output : write ( '\n ' .. rt .. ' ' .. converted .. ';' ) 445end 446end 447output : write ( '\n' ) 448if not fn . receives_array_args then 449-- `opts` and following params are optional: accept minargs..maxargs; else require maxargs. 450local maxargs =# fn . parameters 451local minargs =fn . opts_idx and fn . opts_idx - 1 or maxargs 452local cond , expect 453if minargs == maxargs then 454cond , expect ='args.size != ' .. maxargs , maxargs 455elseif minargs > 0 then 456cond , expect = 457'args.size < ' .. minargs .. ' || args.size > ' .. maxargs , minargs .. ' to ' .. maxargs 458else 459cond , expect ='args.size > ' .. maxargs , 'at most ' .. maxargs 460end 461output : write ( '\n if (' .. cond .. ') {' ) 462output : write ( '\n api_set_error(error, kErrorTypeException, \ 463"Wrong number of arguments: expecting ' .. expect .. ' but got %zu", args.size);' ) 464output : write ( '\n goto cleanup;' ) 465output : write ( '\n }\n' ) 466end 467 468-- Validation/conversion for each argument 469for j =1 , # fn . parameters do 470local converted , param 471param =fn . parameters [ j ] 472converted ='arg_' .. j 473local rt =real_type ( param [ 1 ]) 474-- `opts` + rest are optional: ensure omitted arg keeps its zero-initialized default. 475local optional =fn . opts_idx and j >= fn . opts_idx 476if optional then 477output : write ( '\n if (args.size >= ' .. j .. ') {' ) 478end 479if rt == 'Object' then 480output : write ( '\n ' .. converted .. ' = args.items[' .. ( j - 1 ) .. '];\n' ) 481elseif rt : match ( '^KeyDict_' ) then 482converted ='&' .. converted 483output : write ( '\n if (args.items[' .. ( j - 1 ) .. '].type == kObjectTypeDict) {' ) --luacheck: ignore 631 484output : write ( '\n memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));' ) -- TODO: neeeee 485output : 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) 494output : write ( '\n goto cleanup;' ) 495output : write ( '\n }' ) 496output : 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 503output : write ( '\n memset(' .. converted .. ', 0, sizeof(*' .. converted .. '));' ) 504 505output : write ( '\n } else {' ) 506output : 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) 516output : write ( '\n goto cleanup;' ) 517output : write ( '\n }\n' ) 518else 519if 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 521output : 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) 530output : write ( 531'\n ' .. converted .. ' = (handle_T)args.items[' .. ( j - 1 ) .. '].data.integer;' 532) 533else 534output : write ( '\n if (args.items[' .. ( j - 1 ) .. '].type == kObjectType' .. rt .. ') {' ) 535output : write ( 536'\n ' 537.. converted 538.. ' = args.items[' 539.. ( j - 1 ) 540.. '].data.' 541.. attr_name ( rt ) 542.. ';' 543) 544end 545if 546rt : match ( '^Buffer$' ) 547or rt : match ( '^Window$' ) 548or rt : match ( '^Tabpage$' ) 549or rt : match ( '^Boolean$' ) 550then 551-- accept nonnegative integers for Booleans, Buffers, Windows and Tabpages 552output : write ( 553'\n } else if (args.items[' 554.. ( j - 1 ) 555.. '].type == kObjectTypeInteger && args.items[' 556.. ( j - 1 ) 557.. '].data.integer >= 0) {' 558) 559output : write ( 560'\n ' .. converted .. ' = (handle_T)args.items[' .. ( j - 1 ) .. '].data.integer;' 561) 562end 563if rt : match ( '^Float$' ) then 564-- accept integers for Floats 565output : write ( '\n } else if (args.items[' .. ( j - 1 ) .. '].type == kObjectTypeInteger) {' ) 566output : write ( 567'\n ' .. converted .. ' = (Float)args.items[' .. ( j - 1 ) .. '].data.integer;' 568) 569end 570-- accept empty lua tables as empty dictionaries 571if rt : match ( '^Dict' ) then 572output : 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 579output : write ( '\n ' .. converted .. ' = (Dict)ARRAY_DICT_INIT;' ) 580end 581output : write ( '\n } else {' ) 582output : 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) 592output : write ( '\n goto cleanup;' ) 593output : write ( '\n }\n' ) 594end 595if optional then 596output : write ( '\n }\n' ) 597end 598args [ # args + 1 ] =converted 599end 600 601if fn . textlock then 602output : write ( '\n if (text_locked()) {' ) 603output : write ( '\n api_set_error(error, kErrorTypeException, "%s", get_text_locked_msg());' ) 604output : write ( '\n goto cleanup;' ) 605output : write ( '\n }\n' ) 606end 607 608-- function call 609output : write ( '\n ' ) 610if fn . return_type ~= 'void' then 611-- has a return value, prefix the call with a declaration 612output : write ( fn . return_type .. ' rv = ' ) 613end 614 615-- write the function name and the opening parenthesis 616output : write ( fn . name .. '(' ) 617 618local call_args ={} 619if fn . receives_channel_id then 620table . insert ( call_args , 'channel_id' ) 621end 622 623if fn . receives_array_args then 624table . insert ( call_args , 'args' ) 625end 626 627for _ , a in ipairs ( args ) do 628table . insert ( call_args , a ) 629end 630 631if fn . receives_arena then 632table . insert ( call_args , 'arena' ) 633end 634 635if fn . has_lua_imp then 636table . insert ( call_args , 'NULL' ) 637end 638 639if fn . can_fail then 640table . insert ( call_args , 'error' ) 641end 642 643output : write ( table . concat ( call_args , ', ' )) 644output : write ( ');\n' ) 645 646if 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 649output : write ( '\n if (ERROR_SET(error)) {' ) 650output : write ( '\n goto cleanup;' ) 651output : write ( '\n }\n' ) 652end 653 654local ret_type =real_type ( fn . return_type ) 655if ret_type : match ( '^KeyDict_' ) then 656local table =ret_type : sub ( 9 ) .. '_table' 657output : write ( 658'\n ret = DICT_OBJ(api_keydict_to_dict(&rv, ' 659.. table 660.. ', ARRAY_SIZE(' 661.. table 662.. '), arena));' 663) 664elseif ret_type ~= 'void' then 665output : write ( '\n ret = ' .. real_type ( fn . return_type ): upper () .. '_OBJ(rv);' ) 666end 667output : write ( '\n\ncleanup:' ) 668 669output : write ( '\n return ret;\n}\n\n' ) 670end 671end 672 673--- @type {[string]: gen_api_dispatch.Function, redraw: {impl_name: string, fast: boolean}} 674local remote_fns ={} 675for _ , fn in ipairs ( functions ) do 676if fn . remote then 677remote_fns [ fn . name ] =fn 678end 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 ) 685return 'method_handlers[' .. idx .. '].name' 686end ) 687 688output : write ( 'const MsgpackRpcRequestHandler method_handlers[] = {\n' ) 689for n , name in ipairs ( hashorder ) do 690local fn =remote_fns [ name ] 691fn . handler_id =n - 1 692output : 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 ) 718for i =1 , # headers_to_include do 719if headers_to_include [ i ]: sub ( - 12 ) ~= '.generated.h' then 720output_handle : write ( '\n#include "nvim/' .. headers_to_include [ i ] .. '"' ) 721end 722end 723end 724 725--- @param str string 726local function write_shifted_output ( str , ... ) 727str =str : gsub ( '\n ' , '\n' ) 728str =str : gsub ( '^ ' , '' ) 729str =str : gsub ( ' +$' , '' ) 730output : 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 ) 751local lua_c_function_name =( 'nlua_api_%s' ): format ( fn . name ) 752write_shifted_output ( 753[[ 754 755static int %s(lua_State *lstate) 756{ 757Error err = ERROR_INIT; 758Arena arena = ARENA_EMPTY; 759char *err_param = 0; 760]] , 761lua_c_function_name 762) 763do 764-- `opts` + rest are optional: accept minargs..maxargs; else require maxargs. 765local maxargs =# fn . parameters 766local minargs =fn . opts_idx and fn . opts_idx - 1 or maxargs 767local cond , msg 768if minargs == maxargs then 769cond =( 'lua_gettop(lstate) != %d' ): format ( maxargs ) 770msg =( 'Expected %d argument%s' ): format ( maxargs , maxargs == 1 and '' or 's' ) 771elseif minargs > 0 then 772cond =( 'lua_gettop(lstate) < %d || lua_gettop(lstate) > %d' ): format ( minargs , maxargs ) 773msg =( 'Expected %d to %d arguments' ): format ( minargs , maxargs ) 774else 775cond =( 'lua_gettop(lstate) > %d' ): format ( maxargs ) 776msg =( 'Expected at most %d argument%s' ): format ( maxargs , maxargs == 1 and '' or 's' ) 777end 778write_shifted_output ( 779[[ 780if (%s) { 781api_set_error(&err, kErrorTypeValidation, "%s"); 782goto exit_0; 783} 784]] , 785cond , 786msg 787) 788end 789lua_c_functions [ # lua_c_functions + 1 ] ={ 790binding =lua_c_function_name , 791api =fn . name , 792} 793 794if not fn . fast then 795write_shifted_output ( 796[[ 797if (!nlua_is_deferred_safe()) { 798return luaL_error(lstate, e_fast_api_disabled, "%s"); 799} 800]] , 801fn . name 802) 803end 804 805if fn . textlock then 806write_shifted_output ( [[ 807if (text_locked()) { 808api_set_error(&err, kErrorTypeException, "%%s", get_text_locked_msg()); 809goto exit_0; 810} 811]] ) 812end 813 814local cparams ='' 815local free_code ={} --- @type string[] 816for j =# fn . parameters , 1 , - 1 do 817local param =fn . parameters [ j ] 818local cparam =string . format ( 'arg%u' , j ) 819local param_type =real_type ( param [ 1 ]) 820local extra =param_type == 'Dict' and 'false, ' or '' 821local arg_free_code ='' 822if param_type == 'Object' then 823extra ='true, ' 824arg_free_code =' api_luarefs_free_object(' .. cparam .. ');' 825elseif param [ 1 ] == 'DictOf(LuaRef)' then 826extra ='true, ' 827arg_free_code =' api_luarefs_free_dict(' .. cparam .. ');' 828elseif param [ 1 ] == 'LuaRef' then 829arg_free_code =' api_free_luaref(' .. cparam .. ');' 830end 831local errshift =0 832local 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. 835local optional =fn . opts_idx and j >= fn . opts_idx 836if param_type : match ( '^KeyDict_' ) then 837if optional then 838write_shifted_output ( 839[[ 840%s %s = KEYDICT_INIT; 841if (lua_gettop(lstate) == %d) { 842nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &arena, &err); 843]] , 844param_type , 845cparam , 846j , 847cparam , 848param_type 849) 850else 851write_shifted_output ( 852[[ 853%s %s = KEYDICT_INIT; 854nlua_pop_keydict(lstate, &%s, %s_get_field, &err_param, &arena, &err); 855]] , 856param_type , 857cparam , 858cparam , 859param_type 860) 861end 862cparam ='&' .. cparam 863errshift =1 -- free incomplete dict on error 864arg_free_code =' api_luarefs_free_keydict(' 865.. cparam 866.. ', ' 867.. param_type : sub ( 9 ) 868.. '_table);' 869elseif optional then 870-- Conditionally pop; keep a zero-init `{ 0 }` default when the arg was omitted. 871write_shifted_output ( 872[[ 873%s %s = { 0 }; 874if (lua_gettop(lstate) == %d) { 875%s = nlua_pop_%s(lstate, %s&arena, &err);]] , 876param [ 1 ], 877cparam , 878j , 879cparam , 880param_type , 881extra 882) 883seterr ='\n err_param = "' .. param [ 2 ] .. '";' 884else 885write_shifted_output ( 886[[ 887const %s %s = nlua_pop_%s(lstate, %s&arena, &err);]] , 888param [ 1 ], 889cparam , 890param_type , 891extra 892) 893seterr ='\n err_param = "' .. param [ 2 ] .. '";' 894end 895 896if optional then 897write_shifted_output ( 898[[ 899if (ERROR_SET(&err)) { 900goto exit_%u; 901} 902} 903 904]] , 905# fn . parameters - j + errshift 906) 907else 908write_shifted_output ( [[ 909 910if (ERROR_SET(&err)) {]] .. seterr .. [[ 911 912goto exit_%u; 913} 914 915]] , # fn . parameters - j + errshift ) 916end 917free_code [ # free_code + 1 ] =arg_free_code 918cparams =cparam .. ', ' .. cparams 919end 920if fn . receives_channel_id then 921--- @type string 922cparams ='LUA_INTERNAL_CALL, ' .. cparams 923end 924if fn . receives_arena then 925cparams =cparams .. '&arena, ' 926end 927 928if fn . has_lua_imp then 929cparams =cparams .. 'lstate, ' 930end 931 932if fn . can_fail then 933cparams =cparams .. '&err' 934else 935cparams =cparams : gsub ( ', $' , '' ) 936end 937 938write_shifted_output ( ' ENTER_LUA_ACTIVE_STATE(lstate);\n' ) 939if fn . has_lua_imp and not lua_retstack [ fn . name ] then 940write_shifted_output ( ' const int pretop = lua_gettop(lstate); (void)pretop;\n' ) 941end 942local free_at_exit_code ='' 943for i =1 , # free_code do 944local rev_i =# free_code - i + 1 945local code =free_code [ rev_i ] 946local cur_is_keydict =real_type ( fn . parameters [ i ][ 1 ]): match ( '^KeyDict_' ) 947local prev_is_keydict =i > 1 and real_type ( fn . parameters [ i - 1 ][ 1 ]): match ( '^KeyDict_' ) 948if not cur_is_keydict and ( i == 1 or prev_is_keydict ) then 949free_at_exit_code =free_at_exit_code .. ( '\n%s' ): format ( code ) 950else 951free_at_exit_code =free_at_exit_code .. ( '\nexit_%u:\n%s' ): format ( rev_i , code ) 952end 953end 954local err_throw_code =[[ 955 956exit_0: 957arena_mem_free(arena_finish(&arena)); 958if (ERROR_SET(&err)) { 959luaL_where(lstate, 1); 960if (err_param) { 961lua_pushstring(lstate, "Invalid '"); 962lua_pushstring(lstate, err_param); 963lua_pushstring(lstate, "': "); 964} 965lua_pushstring(lstate, err.msg); 966api_clear_error(&err); 967lua_concat(lstate, err_param ? 5 : 2); 968return lua_error(lstate); 969} 970]] 971if fn . return_type ~= 'void' then 972local return_type =real_type ( fn . return_type ) 973local free_retval ='' 974if fn . ret_alloc then 975free_retval =' api_free_' .. return_type : lower () .. '(ret);' 976end 977write_shifted_output ( ' %s ret = %s(%s);\n' , fn . return_type , fn . name , cparams ) 978 979local ret_type =real_type ( fn . return_type ) 980local ret_mode =( ret_type == 'Object' ) and '&' or '' 981if 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 984if not lua_retstack [ fn . name ] then 985write_shifted_output ( 986' assert((ERROR_SET(&err) || lua_gettop(lstate) == pretop + 1) && "has_lua_imp function must push exactly one return value");\n' 987) 988end 989write_shifted_output ( ' (void)ret;\n' ) 990elseif ret_type : match ( '^KeyDict_' ) then 991write_shifted_output ( ' nlua_push_keydict(lstate, &ret, %s_table);\n' , return_type : sub ( 9 )) 992else 993local special =( fn . since ~= nil and fn . since < 11 ) 994write_shifted_output ( 995' nlua_push_%s(lstate, %sret, %s | kNluaPushFreeRefs);\n' , 996return_type , 997ret_mode , 998special and 'kNluaPushSpecial' or '0' 999) 1000end 1001 1002-- NOTE: we currently assume err_throw needs nothing from arena 1003write_shifted_output ( 1004[[ 1005LEAVE_LUA_ACTIVE_STATE(); 1006%s 1007%s 1008%s 1009return %s; 1010]] , 1011free_retval , 1012free_at_exit_code , 1013err_throw_code , 1014( fn . has_lua_imp and 'lua_gettop(lstate)' or '1' ) 1015) 1016else 1017write_shifted_output ( 1018[[ 1019%s(%s); 1020LEAVE_LUA_ACTIVE_STATE(); 1021%s 1022%s 1023return 0; 1024]] , 1025fn . name , 1026cparams , 1027free_at_exit_code , 1028err_throw_code 1029) 1030end 1031write_shifted_output ( [[ 1032} 1033]] ) 1034end 1035 1036for _ , fn in ipairs ( functions ) do 1037if fn . lua or fn . name : sub ( 1 , 4 ) == '_vim' then 1038process_function ( fn ) 1039end 1040end 1041 1042output : write ( string . format ( 1043[[ 1044void nlua_add_api_functions(lua_State *lstate) 1045{ 1046lua_createtable(lstate, 0, %u); 1047]] , 1048# lua_c_functions 1049)) 1050for _ , func in ipairs ( lua_c_functions ) do 1051output : write ( string . format ( 1052[[ 1053 1054lua_pushcfunction(lstate, &%s); 1055lua_setfield(lstate, -2, "%s");]] , 1056func . binding , 1057func . api 1058)) 1059end 1060output : write ( [[ 1061 1062lua_setfield(lstate, -2, "api"); 1063} 1064]] ) 1065 1066output : close ()