api_types.lua (2198B)
1 local API_TYPES = { 2 Window = 'integer', 3 Tabpage = 'integer', 4 Buffer = 'integer', 5 Boolean = 'boolean', 6 Object = 'any', 7 Integer = 'integer', 8 String = 'string', 9 Array = 'any[]', 10 LuaRef = 'function', 11 Dict = 'table<string,any>', 12 Float = 'number', 13 HLGroupID = 'integer|string', 14 void = 'nil', 15 } 16 17 local typed_container = require('gen.c_grammar').typed_container 18 19 --- Convert an API type to Lua 20 --- @param t string 21 --- @return string 22 local function api_type(t) 23 if vim.startswith(t, '*') then 24 return api_type(t:sub(2)) .. '?' 25 end 26 27 --- @type nvim.c_grammar.Container? 28 local t0 = typed_container:match(t) 29 30 if t0 then 31 local container = t0[1] 32 33 if container == 'ArrayOf' then 34 --- @cast t0 nvim.c_grammar.Container.ArrayOf 35 local ty = api_type(t0[2]) 36 local count = tonumber(t0[3]) 37 if count then 38 return ('[%s]'):format(ty:rep(count, ', ')) 39 else 40 return ty .. '[]' 41 end 42 elseif container == 'Dict' or container == 'DictAs' then 43 --- @cast t0 nvim.c_grammar.Container.Dict 44 return 'vim.api.keyset.' .. t0[2]:gsub('__', '.') 45 elseif container == 'DictOf' then 46 --- @cast t0 nvim.c_grammar.Container.DictOf 47 local ty = api_type(t0[2]) 48 return ('table<string,%s>'):format(ty) 49 elseif container == 'Tuple' then 50 --- @cast t0 nvim.c_grammar.Container.Tuple 51 return ('[%s]'):format(table.concat(vim.tbl_map(api_type, t0[2]), ', ')) 52 elseif container == 'Enum' or container == 'Union' then 53 --- @cast t0 nvim.c_grammar.Container.Enum|nvim.c_grammar.Container.Union 54 return table.concat(vim.tbl_map(api_type, t0[2]), '|') 55 elseif container == 'LuaRefOf' then 56 --- @cast t0 nvim.c_grammar.Container.LuaRefOf 57 local _, as, r = unpack(t0) 58 59 local as1 = {} --- @type string[] 60 for _, a in ipairs(as) do 61 local ty, nm = unpack(a) 62 nm = nm:gsub('%*(.*)$', '%1?') 63 as1[#as1 + 1] = ('%s: %s'):format(nm, api_type(ty)) 64 end 65 66 return ('fun(%s)%s'):format(table.concat(as1, ', '), r and ': ' .. api_type(r) or '') 67 end 68 error('Unknown container type: ' .. container) 69 end 70 71 return API_TYPES[t] or t 72 end 73 74 return api_type