---@class ApiParam ---@field name string ---@field type string ---@field description string ---@class ApiField ---@field name string ---@field type string ---@field description string ---@class ApiStruct ---@field name string ---@field description string ---@field fields ApiField[] ---@class ApiAlias ---@field name string ---@field type string ---@field description string ---@class ApiCallback ---@field name string ---@field description string ---@field returnType string ---@field params? ApiParam[] ---@class ApiFunction ---@field name string ---@field description string ---@field returnType string ---@field params? ApiParam[] ---@class ApiDefine ---@field name string ---@field type string ---@field value string|number ---@field description string ---@class ApiEnumValue ---@field name string ---@field description string ---@field value string|number ---@class ApiEnum ---@field name string ---@field description string ---@field values ApiEnumValue[] ---@class Api ---@field structs ApiStruct[] ---@field aliases ApiAlias[] ---@field callbacks ApiCallback[] ---@field functions ApiFunction[] ---@field defines ApiDefine[] ---@field enums ApiEnum[] ---@class CType ---@field const boolean ---@field base string ---@field ptr integer ---@class ParamInfo ---@field ann string ---@field pre string[]|nil ---@field arg string|nil ---@class GenState ---@field struct_ffi string[] ---@field callback_ffi string[] ---@field function_ffi string[] ---@field define_lines string[] ---@field enum_lines string[] ---@field alias_lines string[] ---@field struct_lines string[] ---@field callback_lines string[] ---@field function_lines string[] ---@field struct_types table ---@field callback_types table ---@field seen_struct_ffi table ---@field seen_alias_ffi table ---@field seen_callback_ffi table ---@field seen_function_ffi table ---@field seen_define table ---@field seen_enum_alias table ---@field seen_constant table ---@field seen_struct_doc table ---@field seen_alias_doc table ---@field seen_callback_doc table ---@field seen_function_doc table ---@param fmt string ---@param ... any ---@return nil local function die(fmt, ...) io.stderr:write("[ERROR] " .. string.format(fmt, ...) .. "\n") os.exit(1) end ---@param file_path string ---@return Api local function load_api_file(file_path) local chunk, err = loadfile(file_path) if not chunk then die("could not load %s: %s", file_path, err) end ---@cast chunk -nil local ok, data = pcall(chunk) if not ok then die("could not run %s: %s", file_path, data) end if type(data) ~= "table" then die("%s did not return a table", file_path) end ---@cast data Api return data end ---Register a name the first time it is seen. ---@param seen table ---@param name string ---@return boolean claimed true when this is the first occurrence local function claim(seen, name) if seen[name] then return false end seen[name] = true return true end ---rlgl's parser output contains C preprocessor fragments in some field types; ---ffi.cdef cannot parse those, so they are dropped. ---@param field ApiField ---@return boolean local function is_usable_field(field) return field.type:sub(1, 1) ~= "#" end ---@param strs ApiStruct[] ---@param aliases ApiAlias[]|nil ---@param seen_structs table ---@param seen_aliases table ---@return string[] local function structs_and_aliases_as_fii_lines(strs, aliases, seen_structs, seen_aliases) local result = {} -- Group aliases by their base struct so we emit them right after the struct is defined ---@type table local alias_by_base = {} for _, a in ipairs(aliases or {}) do local base = a.type:match("^([%w_]+)") if not base then die("could not determine base type for alias %s", a.name) end alias_by_base[base] = alias_by_base[base] or {} table.insert(alias_by_base[base], a) end for _, str in ipairs(strs) do if claim(seen_structs, str.name) then local fields = "" ---@type table local field_names = {} for _, field in ipairs(str.fields) do if is_usable_field(field) and not field_names[field.name] then field_names[field.name] = true local base_type, arr_size = field.type:match("^(.-)(%[%d+%])$") if base_type then fields = fields .. base_type .. " " .. field.name .. arr_size .. "; " else fields = fields .. field.type .. " " .. field.name .. "; " end end end if fields == "" then die("created a struct with an empty fields list") end table.insert(result, string.format("typedef struct %s { %s} %s;", str.name, fields, str.name)) end -- Aliases are emitted once per name, even if the base struct came from an -- earlier API (the typedef is already in the cdef by then). if alias_by_base[str.name] then for _, a in ipairs(alias_by_base[str.name]) do if claim(seen_aliases, a.name) then table.insert(result, string.format("typedef %s %s;", a.type, a.name)) end end end end return result end ---@param callbacks ApiCallback[]|nil ---@param seen table ---@return string[] local function callbacks_as_ffi_lines(callbacks, seen) local result = {} for _, cb in ipairs(callbacks or {}) do if claim(seen, cb.name) then local params = {} for _, p in ipairs(cb.params or {}) do table.insert(params, p.type .. " " .. p.name) end table.insert(result, string.format("typedef %s (*%s)(%s);", cb.returnType, cb.name, table.concat(params, ", "))) end end return result end ---@param funcs ApiFunction[] ---@param seen table ---@return string[] local function functions_as_ffi_lines(funcs, seen) local result = {} for _, func in ipairs(funcs) do if claim(seen, func.name) then local params = {} for _, param in ipairs(func.params or {}) do if param.type == "..." then table.insert(params, "...") else table.insert(params, param.type .. " " .. param.name) end end table.insert(result, string.format("%s %s(%s);", func.returnType, func.name, table.concat(params, ", "))) end end return result end ---@param defs ApiDefine[] ---@param seen table ---@param seen_defines table ---@return string[] local function defines_as_lines(defs, seen, seen_defines) local result = {} for _, def in ipairs(defs) do local def_type = def.type local ignored = def_type == "GUARD" or def_type == "MACRO" or def_type == "UNKNOWN" if not ignored and claim(seen, def.name) then seen_defines[def.name] = true if def_type == "INT" or def_type == "STRING" or def_type == "FLOAT" or def_type == "INT_MATH" then local value = def.value if def_type == "STRING" then value = "\"" .. tostring(def.value) .. "\"" end local str = "" .. def.name .. " = " .. tostring(value) if def.description ~= "" then str = str .. " --" .. def.description end table.insert(result, str) elseif def_type == "FLOAT_MATH" then if def.name == "DEG2RAD" then table.insert(result, "DEG2RAD = 0.017453292519943") elseif def.name == "RAD2DEG" then table.insert(result, "RAD2DEG = 57.295779513082") else die("unknown float math define name %s", def.name) end elseif def_type == "COLOR" then local r, g, b, a = tostring(def.value):match("{%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*}") if not r then die("could not parse color define %s", def.name) end local str = string.format('%s = ffi.new("Color", { r = %s, g = %s, b = %s, a = %s })', def.name, r, g, b, a) table.insert(result, str) else die("unknown define type %s", def_type) end end end return result end ---@param enums ApiEnum[] ---@param seen_aliases table ---@param seen_values table ---@return string[] local function enums_as_lines(enums, seen_aliases, seen_values) local result = {} for _, enum in ipairs(enums) do if claim(seen_aliases, enum.name) then table.insert(result, string.format("---%s", enum.description)) table.insert(result, string.format("---@alias %s", enum.name)) for _, value in ipairs(enum.values) do table.insert(result, string.format("---| `%s` #%s", value.name, value.description)) end end for _, value in ipairs(enum.values) do if claim(seen_values, value.name) then if value.description ~= "" then table.insert(result, string.format("--- %s", value.description)) end table.insert(result, string.format("%s = %s", value.name, value.value)) end end table.insert(result, "") end return result end ---@type table local c_type_map = { ["bool"] = "boolean", ["float"] = "number", ["double"] = "number", ["int"] = "integer", ["unsigned int"] = "integer", ["long"] = "integer", ["unsigned long"] = "integer", ["short"] = "integer", ["unsigned short"] = "integer", ["char"] = "integer", ["unsigned char"] = "integer", } ---@param c_type string ---@return string local function map_type(c_type) -- Strip leading "const " first so "const char *" and "const void *" match cleanly c_type = c_type:gsub("^const%s+", "") -- Special cases for C strings and void pointers in Raylib if c_type == "char *" or c_type:match("^char%[%d+%]$") then return "string" elseif c_type == "void *" or c_type == "rAudioBuffer *" or c_type == "rAudioProcessor *" or c_type == "va_list" then return "ffi.cdata*" end -- Fixed-size arrays like "float[4]" or "Matrix[2]" local base_type = c_type:match("^(.-)%[%d+%]$") if base_type then return map_type(base_type) .. "[]" end -- Pointers like "int *" or "Rectangle **" local ptr_base = c_type:match("^(.-)%s*%*$") if ptr_base then return map_type(ptr_base) .. "[]" end return c_type_map[c_type] or c_type end ---Split a C type into pointer depth, constness and base name. ---@param c_type string ---@return CType local function parse_ctype(c_type) local s = c_type:gsub("^%s+", ""):gsub("%s+$", "") local is_const = false if s:match("^const%s+") then is_const = true s = s:gsub("^const%s+", "") end local ptr = 0 while true do local stripped = s:gsub("%s*%*%s*$", "") if stripped == s then break end ptr = ptr + 1 s = stripped:gsub("%s+$", "") -- const after the pointer is not used by these APIs, but tolerate it s = s:gsub("^const%s+", "") end return { const = is_const, base = s, ptr = ptr } end ---@param aliases ApiAlias[] ---@param seen table ---@return string[] local function aliases_as_lines(aliases, seen) local result = {} for _, alias in ipairs(aliases) do if claim(seen, alias.name) then table.insert(result, string.format("---%s", alias.description)) table.insert(result, string.format("---@alias %s %s", alias.name, map_type(alias.type))) table.insert(result, "") end end return result end ---@param strs ApiStruct[] ---@param seen table ---@return string[] local function structs_as_lines(strs, seen) local result = {} for _, str in ipairs(strs) do if claim(seen, str.name) then table.insert(result, string.format("---%s", str.description)) table.insert(result, string.format("---@class %s", str.name)) ---@type table local field_names = {} for _, field in ipairs(str.fields) do if is_usable_field(field) and not field_names[field.name] then field_names[field.name] = true table.insert(result, string.format("---@field %s %s %s", field.name, map_type(field.type), field.description)) end end table.insert(result, "") end end return result end ---@param callbacks ApiCallback[] ---@param seen table ---@return string[] local function callbacks_as_lines(callbacks, seen) local result = {} for _, c in ipairs(callbacks) do if claim(seen, c.name) then if c.description ~= "" then table.insert(result, string.format("---%s", c.description)) end local params = "" if c.params then for i, param in ipairs(c.params) do params = params .. param.name .. ": " .. map_type(param.type) if #c.params > 1 and i < #c.params then params = params .. ", " end end end local ret = "" if c.returnType ~= "void" then ret = ": " .. map_type(c.returnType) end table.insert(result, string.format("---@alias %s fun(%s)%s", c.name, params, ret)) table.insert(result, "") end end return result end ---@type table local param_enum_map = { -- By parameter name across Raylib: ["key"] = "KeyboardKey", ["logLevel"] = "TraceLogLevel", ["cursor"] = "MouseCursor", ["axis"] = "GamepadAxis", ["uniformType"] = "ShaderUniformDataType", ["filter"] = "TextureFilter", ["wrap"] = "TextureWrap", ["gesture"] = "Gesture", ["mapType"] = "MaterialMapIndex", -- Disambiguated by FunctionName.paramName: ["IsWindowState.flag"] = "ConfigFlags", ["SetWindowState.flags"] = "ConfigFlags", ["ClearWindowState.flags"] = "ConfigFlags", ["SetConfigFlags.flags"] = "ConfigFlags", ["SetGesturesEnabled.flags"] = "Gesture", ["BeginBlendMode.mode"] = "BlendMode", ["UpdateCamera.mode"] = "CameraMode", ["LoadTextureCubemap.layout"] = "CubemapLayout", ["IsMouseButtonPressed.button"] = "MouseButton", ["IsMouseButtonDown.button"] = "MouseButton", ["IsMouseButtonReleased.button"] = "MouseButton", ["IsMouseButtonUp.button"] = "MouseButton", ["IsGamepadButtonPressed.button"] = "GamepadButton", ["IsGamepadButtonDown.button"] = "GamepadButton", ["IsGamepadButtonReleased.button"] = "GamepadButton", ["IsGamepadButtonUp.button"] = "GamepadButton", } ---@type table local return_enum_map = { ["GetKeyPressed"] = "KeyboardKey", ["GetGamepadButtonPressed"] = "GamepadButton", ["GetGestureDetected"] = "Gesture", } ---@param dst string[] ---@param src string[] ---@return nil local function append_all(dst, src) for _, line in ipairs(src) do dst[#dst + 1] = line end end ---@param func ApiFunction ---@param param ApiParam ---@param index integer ---@param pname string ---@param struct_types table ---@param callback_types table ---@return ParamInfo local function param_info(func, param, index, pname, struct_types, callback_types) local ct = parse_ctype(param.type) local var = "_a" .. index if ct.ptr == 0 then if callback_types[ct.base] then return { ann = "ffi.cdata*", pre = nil, arg = nil } end local ptype = param_enum_map[func.name .. "." .. pname] or ((param.type == "int" or param.type == "unsigned int") and param_enum_map[pname]) or map_type(param.type) return { ann = ptype, pre = nil, arg = nil } end -- char ** / const char **: array of Lua strings if ct.base == "char" and ct.ptr == 2 then local array = 'to_array("const char *", ' .. pname .. ")" if not ct.const then array = 'ffi.cast("char **", ' .. array .. ")" end return { ann = "string[]|ffi.cdata*", arg = var, pre = { "local " .. var, 'if type(' .. pname .. ') == "table" then ' .. var .. " = " .. array, "else " .. var .. " = " .. pname .. " end", }, } end -- const char * accepts a Lua string; non-const char * is a mutable buffer if ct.base == "char" and ct.ptr == 1 then if ct.const then return { ann = "string", pre = nil, arg = nil } end return { ann = "ffi.cdata*", pre = nil, arg = nil } end if ct.base == "unsigned char" and ct.ptr == 1 and ct.const then return { ann = "string|integer[]|ffi.cdata*", arg = var, pre = { "local " .. var, string.format('if type(%s) == "string" then %s = ffi.cast("const unsigned char *", %s)', pname, var, pname), string.format('elseif type(%s) == "table" then %s = to_array("unsigned char", %s)', pname, var, pname), "else " .. var .. " = " .. pname .. " end", }, } end if ct.base == "void" and ct.ptr == 1 and ct.const then return { ann = "string|ffi.cdata*", arg = var, pre = { "local " .. var, string.format('if type(%s) == "string" then %s = ffi.cast("const void *", %s)', pname, var, pname), "else " .. var .. " = " .. pname .. " end", }, } end -- const T * where T is a scalar or a known struct/alias: tables become arrays if ct.const and ct.ptr == 1 and (c_type_map[ct.base] ~= nil or struct_types[ct.base]) then return { ann = map_type(ct.base) .. "[]|ffi.cdata*", arg = var, pre = { "local " .. var, string.format('if type(%s) == "table" then %s = to_array("%s", %s)', pname, var, ct.base, pname), "else " .. var .. " = " .. pname .. " end", }, } end return { ann = "ffi.cdata*", pre = nil, arg = nil } end ---@param func ApiFunction ---@return string|nil local function return_ann(func) local ct = parse_ctype(func.returnType) if ct.ptr == 0 then if ct.base == "void" then return nil end return return_enum_map[func.name] or map_type(func.returnType) end if ct.base == "char" and ct.ptr == 1 then return ct.const and "string" or "string|nil" end return "ffi.cdata*" end ---@param funcs ApiFunction[] ---@param seen table ---@param struct_types table ---@param callback_types table ---@return string[] local function functions_as_lines(funcs, seen, struct_types, callback_types) local result = {} for _, func in ipairs(funcs) do if claim(seen, func.name) then if func.name == "TextFormat" then -- LuaJIT cannot forward Lua varargs to a C vararg function with -- unknown types, so format in Lua and never call C here. table.insert(result, "---" .. func.description) table.insert(result, "---@param fmt string") table.insert(result, "---@param ... any") table.insert(result, "---@return string") table.insert(result, "function TextFormat(fmt, ...)") table.insert(result, ' if select("#", ...) == 0 then') table.insert(result, " return fmt") table.insert(result, " end") table.insert(result, " return string_format(fmt, ...)") table.insert(result, "end") elseif func.name == "TraceLog" then table.insert(result, "---" .. func.description) table.insert(result, "---@param level TraceLogLevel") table.insert(result, "---@param fmt string") table.insert(result, "---@param ... any") table.insert(result, "---@return nil") table.insert(result, "function TraceLog(level, fmt, ...)") table.insert(result, ' if select("#", ...) == 0 then') table.insert(result, ' C.TraceLog(level, "%s", fmt)') table.insert(result, " else") table.insert(result, ' C.TraceLog(level, "%s", string_format(fmt, ...))') table.insert(result, " end") table.insert(result, "end") else table.insert(result, "---" .. func.description) local sig = {} local args = {} local pre = {} local ann = {} for i, param in ipairs(func.params or {}) do local pname = (param.name == "end") and "_end" or param.name if param.type == "..." then table.insert(ann, "---@param ... any") table.insert(sig, "...") table.insert(args, "...") else local info = param_info(func, param, i, pname, struct_types, callback_types) table.insert(ann, string.format("---@param %s %s", pname, info.ann)) if info.pre then append_all(pre, info.pre) end table.insert(sig, pname) table.insert(args, info.arg or pname) end end for _, line in ipairs(ann) do table.insert(result, line) end local ra = return_ann(func) if ra then table.insert(result, "---@return " .. ra) end local param_str = table.concat(sig, ", ") local call = string.format("C.%s(%s)", func.name, table.concat(args, ", ")) table.insert(result, string.format("function %s(%s)", func.name, param_str)) for _, line in ipairs(pre) do table.insert(result, " " .. line) end local ct = parse_ctype(func.returnType) if ra == nil then table.insert(result, " " .. call) elseif ct.base == "char" and ct.ptr == 1 and ct.const then table.insert(result, " local _r = " .. call) table.insert(result, ' return _r ~= nil and ffi.string(_r) or ""') elseif ct.base == "char" and ct.ptr == 1 then table.insert(result, " local _r = " .. call) table.insert(result, " if _r == nil then return nil end") table.insert(result, " return ffi.string(_r)") else table.insert(result, " return " .. call) end table.insert(result, "end") end table.insert(result, "") end end return result end ---@param tbl table ---@return integer local function count_keys(tbl) local n = 0 for _ in pairs(tbl) do n = n + 1 end return n end ---@return GenState local function new_state() return { struct_ffi = {}, callback_ffi = {}, function_ffi = {}, define_lines = {}, enum_lines = {}, alias_lines = {}, struct_lines = {}, callback_lines = {}, function_lines = {}, struct_types = {}, callback_types = {}, seen_struct_ffi = {}, seen_alias_ffi = {}, seen_callback_ffi = {}, seen_function_ffi = {}, seen_define = {}, seen_enum_alias = {}, seen_constant = {}, seen_struct_doc = {}, seen_alias_doc = {}, seen_callback_doc = {}, seen_function_doc = {}, } end ---@param api Api ---@param st GenState ---@return nil local function wapi(api, st) append_all(st.struct_ffi, structs_and_aliases_as_fii_lines( api.structs, api.aliases, st.seen_struct_ffi, st.seen_alias_ffi)) append_all(st.callback_ffi, callbacks_as_ffi_lines(api.callbacks, st.seen_callback_ffi)) append_all(st.function_ffi, functions_as_ffi_lines(api.functions, st.seen_function_ffi)) append_all(st.define_lines, defines_as_lines(api.defines, st.seen_constant, st.seen_define)) append_all(st.enum_lines, enums_as_lines(api.enums, st.seen_enum_alias, st.seen_constant)) append_all(st.alias_lines, aliases_as_lines(api.aliases, st.seen_alias_doc)) append_all(st.struct_lines, structs_as_lines(api.structs, st.seen_struct_doc)) append_all(st.callback_lines, callbacks_as_lines(api.callbacks, st.seen_callback_doc)) append_all(st.function_lines, functions_as_lines( api.functions, st.seen_function_doc, st.struct_types, st.callback_types)) end local lines = {} ---@param line string ---@return nil local function aline(line) lines[#lines + 1] = line -- append a line. end -- Load order determines output order. ---@type string[] local api_paths = { "build/api/raylib_api.lua", "build/api/rlgl_api.lua", "build/api/raymath_api.lua", "build/api/raygui_api.lua", } ---@type Api[] local apis = {} for _, path in ipairs(api_paths) do apis[#apis + 1] = load_api_file(path) end local st = new_state() ---@type string[] local api_labels = {} for i, api in ipairs(apis) do for _, str in ipairs(api.structs) do st.struct_types[str.name] = true end for _, alias in ipairs(api.aliases) do st.struct_types[alias.name] = true end for _, cb in ipairs(api.callbacks) do st.callback_types[cb.name] = true end local label = api_paths[i]:match("([^/]+)_api%.lua$") or api_paths[i] api_labels[#api_labels + 1] = string.format("%s (%d functions)", label, #api.functions) end for _, api in ipairs(apis) do wapi(api, st) end ---@type string local out_path = (arg and arg[1]) or "hate-no-d.lua" local n_functions = count_keys(st.seen_function_doc) local n_structs = count_keys(st.seen_struct_doc) local n_aliases = count_keys(st.seen_alias_doc) local n_callbacks = count_keys(st.seen_callback_doc) local n_defines = count_keys(st.seen_define) local n_enums = count_keys(st.seen_enum_alias) aline("--[[") aline(string.format(" %s - generated by generate.lua, do not edit.", out_path)) aline(" APIs: " .. table.concat(api_labels, ", ")) aline(string.format(" %d functions, %d structs, %d aliases, %d callbacks, %d defines, %d enums", n_functions, n_structs, n_aliases, n_callbacks, n_defines, n_enums)) aline("]]") aline("") aline('local ffi = require("ffi")') aline("") aline("ffi.cdef[[") aline("typedef struct rAudioBuffer rAudioBuffer;") aline("typedef struct rAudioProcessor rAudioProcessor;") for _, l in ipairs(st.struct_ffi) do aline(l) end aline("") for _, l in ipairs(st.callback_ffi) do aline(l) end aline("") for _, l in ipairs(st.function_ffi) do aline(l) end aline("]]") aline("") aline("local C = ffi.C") aline("local string_format = string.format") aline("local type, select = type, select") aline("") aline("local function to_array(ct, t, n)") aline(" n = n or #t") aline(' local a = ffi.new(ct .. "[?]", n)') aline(" for i = 1, n do") aline(" a[i - 1] = t[i]") aline(" end") aline(" return a") aline("end") aline("") for _, l in ipairs(st.define_lines) do aline(l) end aline("") for _, l in ipairs(st.enum_lines) do aline(l) end aline("") for _, l in ipairs(st.alias_lines) do aline(l) end aline("") for _, l in ipairs(st.struct_lines) do aline(l) end aline("") for _, l in ipairs(st.callback_lines) do aline(l) end aline("") for _, l in ipairs(st.function_lines) do aline(l) end local fh, open_err = io.open(out_path, "wb") if not fh then die("could not open %s for writing: %s", out_path, open_err) end ---@cast fh -nil fh:write(table.concat(lines, "\n")) fh:write("\n") fh:close() io.stderr:write(string.format( "generate: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d defines, %d enums)\n", out_path, n_functions, n_structs, n_aliases, n_callbacks, n_defines, n_enums ))