hate-no-d/gen-hate-no-d.lua
pedro-bento d551f6d3a4
All checks were successful
release / linux/aarch64 (pull_request) Successful in 2m2s
release / linux/armv7 (pull_request) Successful in 2m15s
release / linux/i686 (pull_request) Successful in 2m5s
release / linux/x86_64 (pull_request) Successful in 2m31s
release / android (pull_request) Successful in 2m59s
release / freebsd/x86_64 (pull_request) Successful in 6m11s
release / windows/i686 (pull_request) Successful in 2m6s
release / windows/x86_64 (pull_request) Successful in 2m14s
Add raygui
2026-10-24 22:48:18 +01:00

1124 lines
30 KiB
Lua

#!/usr/bin/env luajit
--[[
gen-hate-no-d.lua - generate hate-no-d.lua from raylib's own parser output.
The generated file contains:
* one ffi.cdef block with every typedef/struct/alias/callback/prototype
* Lua constants (enums, #defines, colors)
* one Lua wrapper per C function, with ffi.string() handling for char*
returns, array conversions for const T* params, in/out helpers for
asset structs (Image*, Mesh*, ...) and callback pinning
* complete LuaCATS annotations (---@class / @field / @param / @return)
Inputs are plain Lua tables produced by raylib's tools/rlparser. The Makefile
generates them into build/api (the parser itself into build/rlparser), so a
build never writes into raylib's tools/ tree:
build/rlparser -i submodules/raylib/src/raylib.h \
-o build/api/raylib_api.lua -f LUA -d RLAPI
build/rlparser -i submodules/raylib/src/rlgl.h \
-o build/api/rlgl_api.lua -f LUA -d RLAPI -t "RLGL IMPLEMENTATION"
build/rlparser -i submodules/raylib/src/raymath.h \
-o build/api/raymath_api.lua -f LUA -d RMAPI
build/rlparser -i submodules/raygui/src/raygui.h \
-o build/api/raygui_api.lua -f LUA -d RAYGUIAPI
Run from the repository root; every table above is required and the result is
always written to hate-no-d.lua.
raymath needs no extra translation unit: raylib's own rcore.c defines
RAYMATH_IMPLEMENTATION before including raymath.h, so libraylib.a already
contains all 146 raymath symbols (verified with nm). Linking the library
with --whole-archive exposes them to ffi.C.
raygui is header-only, its implementation is force-included into the CLI's
translation unit (-DRAYGUI_IMPLEMENTATION -include .../raygui.h), so its
symbols land in the executable and --whole-archive is not involved.
]]
local RAYLIB_API = "build/api/raylib_api.lua"
local RLGL_API = "build/api/rlgl_api.lua"
local RAYMATH_API = "build/api/raymath_api.lua"
local RAYGUI_API = "build/api/raygui_api.lua"
local OUT = "hate-no-d.lua"
local function die(fmt, ...)
io.stderr:write("gen-hate-no-d: " .. string.format(fmt, ...) .. "\n")
os.exit(1)
end
----------------------------------------------------------------------------
-- loading
----------------------------------------------------------------------------
local function load_api(path)
local chunk, err = loadfile(path)
if not chunk then
die("cannot load %s: %s", path, err)
end
local ok, data = pcall(chunk)
if not ok then
die("cannot run %s: %s", path, data)
end
if type(data) ~= "table" then
die("%s did not return a table", path)
end
return data
end
local raylib_api = load_api(RAYLIB_API)
local raygui_api = load_api(RAYGUI_API)
-- Merge order matters: raylib defines the base types (Texture, ...) that raygui
-- redeclares in its standalone fallback, so raylib always goes first.
local apis = {
raylib_api,
load_api(RLGL_API),
load_api(RAYMATH_API),
raygui_api,
}
----------------------------------------------------------------------------
-- type model
----------------------------------------------------------------------------
local SCALAR = {
["void"] = true, bool = true, char = true, short = true, int = true,
long = true, float = true, double = true,
["unsigned char"] = true, ["unsigned short"] = true,
["unsigned int"] = true, ["unsigned long"] = true,
["signed char"] = true, ["long long"] = true, ["size_t"] = true,
}
local INTEGER = {
char = true, short = true, int = true, long = true,
["unsigned char"] = true, ["unsigned short"] = true,
["unsigned int"] = true, ["unsigned long"] = true,
["signed char"] = true, ["long long"] = true, ["size_t"] = true,
}
local NUMBER = { float = true, double = true }
local STRUCTS, ALIASES, CALLBACKS = {}, {}, {}
local DEFS = {}
local function norm(s)
return (s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", ""))
end
-- Parse a raylib parser type string into base / pointer depth / const / array.
local function parse_type(t)
local s = norm(t)
local array = s:match("%[(%d+)%]%s*$")
if array then
s = s:gsub("%[%d+%]%s*$", "")
s = norm(s)
end
local is_const = false
if s:match("^const ") then
is_const = true
s = norm(s:sub(7))
end
local ptr = select(2, s:gsub("%*", ""))
s = norm((s:gsub("%*", "")))
return { base = s, ptr = ptr, const = is_const, array = tonumber(array) }
end
local function is_structish(base)
return STRUCTS[base] ~= nil or ALIASES[base] ~= nil
end
----------------------------------------------------------------------------
-- merge the three API tables
----------------------------------------------------------------------------
local FUNCS = {}
-- rlparser is line-oriented and does not evaluate the preprocessor: rlgl.h
-- struct fields guarded by #if/#endif leak into the output as bogus fields
-- ("#endif indices", "#if defined(...) unsigned int * indices"). Drop those
-- and keep the first real field with a given name.
local function sanitize_fields(fields)
local clean, seen = {}, {}
for _, f in ipairs(fields) do
local ftype = norm(f.type or "")
local fname = norm(f.name or "")
if fname ~= "" and not fname:match("^#") and not ftype:match("^#") and not seen[fname] then
seen[fname] = true
clean[#clean + 1] = f
end
end
return clean
end
local function add_api(data)
for _, s in ipairs(data.structs or {}) do
if not STRUCTS[s.name] and not ALIASES[s.name] then
STRUCTS[s.name] = {
kind = "struct",
name = s.name,
fields = sanitize_fields(s.fields or {}),
description = s.description,
}
DEFS[#DEFS + 1] = STRUCTS[s.name]
end
end
for _, a in ipairs(data.aliases or {}) do
if not ALIASES[a.name] and not STRUCTS[a.name] then
-- rlparser stores the target in `type` and the new name in `name`.
ALIASES[a.name] = {
kind = "alias",
name = a.name,
target = a.type,
description = a.description,
}
DEFS[#DEFS + 1] = ALIASES[a.name]
end
end
for _, c in ipairs(data.callbacks or {}) do
if not CALLBACKS[c.name] then
CALLBACKS[c.name] = c
end
end
for _, f in ipairs(data.functions or {}) do
FUNCS[#FUNCS + 1] = f
end
end
for _, data in ipairs(apis) do
add_api(data)
end
-- TraceLogCallback carries va_list, which LuaJIT cannot pass to a Lua
-- callback; drop the callback and the single function using it.
CALLBACKS.TraceLogCallback = nil
local SKIP = {
SetTraceLogCallback = true,
}
local function params_of(f)
return f.params or {}
end
local function is_skipped(f)
if SKIP[f.name] then
return true
end
for _, p in ipairs(params_of(f)) do
if norm(p.type) == "va_list" then
return true
end
end
return false
end
----------------------------------------------------------------------------
-- validation
----------------------------------------------------------------------------
local function check_type(t, where)
local p = parse_type(t)
if p.base == "..." or p.base == "va_list" then
return
end
if SCALAR[p.base] or is_structish(p.base) or CALLBACKS[p.base] then
return
end
if p.ptr > 0 then
return -- opaque pointer (rAudioBuffer *, ...)
end
die("unknown type %q in %s", p.base, where)
end
local func_names = {}
for _, f in ipairs(FUNCS) do
if func_names[f.name] then
die("duplicate function name %s", f.name)
end
func_names[f.name] = true
if not is_skipped(f) then
check_type(f.returnType, f.name .. " return")
for _, p in ipairs(params_of(f)) do
check_type(p.type, f.name .. " param " .. p.name)
end
end
end
for _, def in ipairs(DEFS) do
if def.kind == "struct" then
for _, f in ipairs(def.fields) do
check_type(f.type, def.name .. "." .. f.name)
end
else
check_type(def.target, def.name .. " alias")
end
end
-- Opaque struct names (forward declarations in the cdef).
local OPAQUE = {}
local function scan_opaque(t)
local p = parse_type(t)
if p.base == "..." or p.base == "va_list" then
return
end
if SCALAR[p.base] or is_structish(p.base) or CALLBACKS[p.base] then
return
end
OPAQUE[p.base] = true
end
for _, def in ipairs(DEFS) do
if def.kind == "struct" then
for _, f in ipairs(def.fields) do
scan_opaque(f.type)
end
end
end
for _, f in ipairs(FUNCS) do
if not is_skipped(f) then
scan_opaque(f.returnType)
for _, p in ipairs(params_of(f)) do
scan_opaque(p.type)
end
end
end
local opaque_names = {}
for name in pairs(OPAQUE) do
opaque_names[#opaque_names + 1] = name
end
table.sort(opaque_names)
----------------------------------------------------------------------------
-- dependency order (typedefs must be declared before use)
----------------------------------------------------------------------------
local function deps_of(def)
local deps = {}
local function add(t)
local p = parse_type(t)
if is_structish(p.base) and p.base ~= def.name then
deps[#deps + 1] = p.base
end
end
if def.kind == "struct" then
for _, f in ipairs(def.fields) do
add(f.type)
end
else
add(def.target)
end
return deps
end
local ordered = {}
local state = {}
local function visit(name)
if state[name] == "done" then
return
end
if state[name] == "active" then
die("cyclic typedef involving %s", name)
end
local def = STRUCTS[name] or ALIASES[name]
if not def then
return
end
state[name] = "active"
for _, dep in ipairs(deps_of(def)) do
visit(dep)
end
state[name] = "done"
ordered[#ordered + 1] = def
end
for _, def in ipairs(DEFS) do
visit(def.name)
end
----------------------------------------------------------------------------
-- C rendering
----------------------------------------------------------------------------
local function c_base(base)
if SCALAR[base] or is_structish(base) or CALLBACKS[base] then
return base
end
return "struct " .. base
end
local function c_type(t)
local p = parse_type(t)
if p.base == "..." then
return "..."
end
local s = c_base(p.base)
if p.ptr > 0 then
s = s .. " " .. string.rep("*", p.ptr)
end
if p.const then
s = "const " .. s
end
return s
end
local function c_field(ftype, fname)
local p = parse_type(ftype)
local base = c_base(p.base)
if p.array then
return base .. " " .. fname .. "[" .. p.array .. "]"
end
if p.ptr > 0 then
return base .. " " .. string.rep("*", p.ptr) .. fname
end
return base .. " " .. fname
end
----------------------------------------------------------------------------
-- LuaCATS rendering
----------------------------------------------------------------------------
local CHAR_BUFFER = "raylib.char_buffer"
local CSTRING_ARRAY = "raylib.cstring_array"
local function ann_scalar(base)
if base == "bool" then
return "boolean"
end
if INTEGER[base] then
return "integer"
end
if NUMBER[base] then
return "number"
end
return nil
end
local function ann_value(base)
local scalar = ann_scalar(base)
if scalar then
return scalar
end
if is_structish(base) then
return "raylib." .. base
end
return "ffi.cdata*"
end
local function ann_field(ftype)
local p = parse_type(ftype)
if p.array then
if p.base == "char" then
return CHAR_BUFFER
end
local elem = ann_scalar(p.base)
if elem then
return elem .. "[]"
end
if is_structish(p.base) then
return "raylib." .. p.base .. "[]"
end
return "ffi.cdata*"
end
if p.ptr > 0 then
if p.base == "char" then
return p.ptr == 1 and CHAR_BUFFER or CSTRING_ARRAY
end
if p.base == "void" then
return "ffi.cdata*"
end
if INTEGER[p.base] then
return "integer[]"
end
if NUMBER[p.base] then
return "number[]"
end
if is_structish(p.base) then
return "raylib." .. p.base .. "[]"
end
return "ffi.cdata*"
end
return ann_value(p.base)
end
-- Struct pointers that are genuinely in/out: the caller passes the handle and
-- gets the (possibly mutated) handle back.
local OUT_STRUCT = {
Image = true, Texture2D = true, Mesh = true, Wave = true, Material = true,
Model = true, RenderTexture2D = true, Camera = true, AutomationEventList = true,
}
-- Functions whose struct-pointer parameters are pure outputs. Those params are
-- optional on the Lua side and become extra return values.
local OUT_OVERRIDES = {
MatrixDecompose = { 2, 3, 4 },
}
local function ann_param(p, is_out)
local pt = parse_type(p.type)
if pt.base == "..." then
return "any"
end
if CALLBACKS[pt.base] then
return "raylib." .. pt.base
end
if pt.ptr == 0 then
return ann_value(pt.base)
end
if is_out then
return "raylib." .. pt.base
end
if pt.base == "char" then
if pt.ptr == 1 then
return pt.const and "string" or (CHAR_BUFFER .. "|string")
end
return "string[]|" .. CSTRING_ARRAY
end
if pt.base == "void" then
return "ffi.cdata*|string"
end
if pt.base == "unsigned char" and pt.const then
return "string|integer[]"
end
if pt.const then
local elem = ann_scalar(pt.base)
if elem then
return elem .. "[]"
end
if is_structish(pt.base) then
return "raylib." .. pt.base .. "[]"
end
end
return "ffi.cdata*"
end
local function ann_return(t)
local p = parse_type(t)
if p.base == "void" and p.ptr == 0 then
return "nil"
end
if p.ptr == 0 then
return ann_value(p.base)
end
if p.base == "char" and p.ptr == 1 then
return "string|nil"
end
return "ffi.cdata*"
end
----------------------------------------------------------------------------
-- out-params / array conversions
----------------------------------------------------------------------------
local function out_params(f)
local out = {}
local ret = parse_type(f.returnType)
if ret.base ~= "void" or ret.ptr ~= 0 then
return out
end
if OUT_OVERRIDES[f.name] then
for _, i in ipairs(OUT_OVERRIDES[f.name]) do
out[i] = "out"
end
return out
end
local params = params_of(f)
for i, p in ipairs(params) do
local pt = parse_type(p.type)
if pt.ptr == 1 and not pt.const and OUT_STRUCT[pt.base] then
out[i] = "inout"
end
end
return out
end
-- Convert Lua-friendly argument forms (string / table) to cdata without
-- reassigning the annotated parameter: doing that makes LuaLS warn with
-- cast-local-type. The result goes into an untyped local instead.
local function conversion_for(name, ptype, idx)
local pt = parse_type(ptype)
local var = "_a" .. idx
if pt.base == "unsigned char" and pt.ptr == 1 and pt.const then
return { arg = var, lines = {
"local " .. var,
'if type(' .. name .. ') == "string" then ' .. var .. ' = ffi.cast("const unsigned char *", ' .. name .. ")",
'elseif type(' .. name .. ') == "table" then ' .. var .. ' = to_array("unsigned char", ' .. name .. ")",
"else " .. var .. " = " .. name .. " end",
} }
end
if pt.base == "void" and pt.ptr == 1 then
return { arg = var, lines = {
"local " .. var,
'if type(' .. name .. ') == "string" then ' .. var .. ' = ffi.cast("const void *", ' .. name .. ")",
"else " .. var .. " = " .. name .. " end",
} }
end
if pt.base == "char" and pt.ptr == 2 then
-- raylib takes char** (non-const), but an array of const char* is what a
-- Lua table naturally builds; the cast is safe because these parameters
-- are read-only in practice.
local array = 'to_array("const char *", ' .. name .. ")"
if not pt.const then
array = 'ffi.cast("char **", ' .. array .. ")"
end
return { arg = var, lines = {
"local " .. var,
'if type(' .. name .. ') == "table" then ' .. var .. " = " .. array,
"else " .. var .. " = " .. name .. " end",
} }
end
if pt.const and pt.ptr == 1 and pt.base ~= "char" and pt.base ~= "void" then
return { arg = var, lines = {
"local " .. var,
'if type(' .. name .. ') == "table" then ' .. var .. ' = to_array("' .. pt.base .. '", ' .. name .. ")",
"else " .. var .. " = " .. name .. " end",
} }
end
return nil
end
----------------------------------------------------------------------------
-- emitted source
----------------------------------------------------------------------------
local out = {}
local function w(line)
out[#out + 1] = line or ""
end
local function clean_description(s)
if not s or s == "" then
return nil
end
s = s:gsub("%s+", " "):gsub("^ ", ""):gsub(" $", "")
return s
end
local version = "unknown"
local function find_define(data, name)
for _, d in ipairs(data.defines or {}) do
if d.name == name then
return d.value
end
end
return nil
end
version = tostring(find_define(raylib_api, "RAYLIB_VERSION") or "unknown")
local raygui_version = tostring(find_define(raygui_api, "RAYGUI_VERSION") or "unknown")
w("--[[")
w(" hate-no-d.lua - generated by gen-hate-no-d.lua, do not edit.")
w("")
w(" raylib " .. version .. " / rlgl / raymath / raygui " .. raygui_version)
w(" Functions: " .. tostring(#FUNCS))
w("")
w(" raymath symbols come from rcore.o (RAYMATH_IMPLEMENTATION) in libraylib.a.")
w(" raygui symbols come from a forced -include of raygui.h (RAYGUI_IMPLEMENTATION).")
w("]]")
w("")
w('local ffi = require("ffi")')
w("")
w("ffi.cdef[[")
for _, name in ipairs(opaque_names) do
w("struct " .. name .. ";")
end
if #opaque_names > 0 then
w("")
end
for _, def in ipairs(ordered) do
if def.kind == "struct" then
w("typedef struct " .. def.name .. " {")
for _, f in ipairs(def.fields) do
w(" " .. c_field(f.type, f.name) .. ";")
end
w("} " .. def.name .. ";")
else
w("typedef " .. c_type(def.target) .. " " .. def.name .. ";")
end
w("")
end
for _, cb in ipairs({ CALLBACKS.AudioCallback, CALLBACKS.LoadFileDataCallback,
CALLBACKS.SaveFileDataCallback, CALLBACKS.LoadFileTextCallback,
CALLBACKS.SaveFileTextCallback }) do
if cb then
local args = {}
for _, p in ipairs(params_of(cb)) do
if parse_type(p.type).base == "..." then
args[#args + 1] = "..."
else
args[#args + 1] = c_type(p.type) .. " " .. p.name
end
end
if #args == 0 then
args[1] = "void"
end
w("typedef " .. c_type(cb.returnType) .. " (*" .. cb.name .. ")(" .. table.concat(args, ", ") .. ");")
w("")
end
end
for _, f in ipairs(FUNCS) do
if not is_skipped(f) then
local args = {}
for _, p in ipairs(params_of(f)) do
if parse_type(p.type).base == "..." then
args[#args + 1] = "..."
else
args[#args + 1] = c_type(p.type) .. " " .. p.name
end
end
if #args == 0 then
args[1] = "void"
end
w(c_type(f.returnType) .. " " .. f.name .. "(" .. table.concat(args, ", ") .. ");")
end
end
w("]]")
w("")
w("local C = ffi.C")
w("local string_format = string.format")
w("local ffi_string = ffi.string")
w("local type, select = type, select")
w("")
w("local M = {}")
w("")
w("-- Raw namespace for hot paths that want to skip the Lua wrapper.")
w("---@type ffi.namespace*")
w("M.C = C")
w("")
w("---@class raylib.char_buffer")
w("---@field [integer] integer")
w("")
w("---@class raylib.cstring_array")
w("---@field [integer] ffi.cdata*")
w("")
w("local pinned = {}")
w("local callback_cache = {}")
w("local function pin(ctype, fn)")
w(" if fn == nil then")
w(" return nil")
w(" end")
w(" local by_type = callback_cache[fn]")
w(" if by_type == nil then")
w(" by_type = {}")
w(" callback_cache[fn] = by_type")
w(" end")
w(" local cb = by_type[ctype]")
w(" if cb == nil then")
w(" cb = ffi.cast(ctype, fn)")
w(" by_type[ctype] = cb")
w(" pinned[#pinned + 1] = cb")
w(" end")
w(" return cb")
w("end")
w("")
w("local function to_array(ct, t, n)")
w(" n = n or #t")
w(' local a = ffi.new(ct .. "[?]", n)')
w(" for i = 1, n do")
w(" a[i - 1] = t[i]")
w(" end")
w(" return a")
w("end")
w("")
----------------------------------------------------------------------------
-- constants
----------------------------------------------------------------------------
local enum_constants = {}
local seen_const = {}
for _, data in ipairs(apis) do
for _, enum in ipairs(data.enums or {}) do
w("---@enum raylib." .. enum.name)
w("M." .. enum.name .. " = {")
for _, v in ipairs(enum.values or {}) do
local value
if type(v.value) == "number" then
value = tostring(v.value)
elseif type(v.value) == "string" then
value = string.format("%q", v.value)
else
value = tostring(v.value)
end
w(" " .. v.name .. " = " .. value .. ",")
enum_constants[v.name] = enum.name
seen_const[v.name] = true
end
w("}")
w("")
end
end
for _, data in ipairs(apis) do
for _, enum in ipairs(data.enums or {}) do
for _, v in ipairs(enum.values or {}) do
w("---@type raylib." .. enum.name)
w("M." .. v.name .. " = M." .. enum.name .. "." .. v.name)
end
end
end
w("")
local alias_defines = {}
local pi_value = nil
local function eval_float_math(expr)
expr = expr:gsub("PI", tostring(pi_value or math.pi))
expr = expr:gsub("(%d)f", "%1")
local chunk = load("return " .. expr)
if not chunk then
return nil
end
local ok, value = pcall(chunk)
if not ok or type(value) ~= "number" then
return nil
end
return value
end
for _, data in ipairs(apis) do
for _, d in ipairs(data.defines or {}) do
if not seen_const[d.name] then
local dtype = d.type
local emitted = false
if dtype == "FLOAT" or dtype == "INT" then
if type(d.value) == "number" then
if d.name == "PI" then
pi_value = d.value
end
w("M." .. d.name .. " = " .. tostring(d.value))
emitted = true
end
elseif dtype == "FLOAT_MATH" then
local value = eval_float_math(tostring(d.value))
if value then
w("M." .. d.name .. " = " .. tostring(value))
emitted = true
end
elseif dtype == "STRING" then
w("M." .. d.name .. " = " .. string.format("%q", tostring(d.value)))
emitted = true
elseif dtype == "COLOR" then
local r, g, b, a = tostring(d.value):match("{%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)%s*}")
if r then
w("---@type raylib.Color")
w(string.format('M.%s = ffi.new("Color", { r = %s, g = %s, b = %s, a = %s })',
d.name, r, g, b, a))
emitted = true
end
elseif dtype == "UNKNOWN" then
local target = tostring(d.value)
if target:match("^[A-Z_][A-Z0-9_]*$") then
alias_defines[#alias_defines + 1] = { name = d.name, target = target }
end
end
if emitted then
seen_const[d.name] = true
end
end
end
end
for _, a in ipairs(alias_defines) do
if seen_const[a.target] then
local enum = enum_constants[a.target]
if enum then
w("---@type raylib." .. enum)
end
w("M." .. a.name .. " = M." .. a.target)
end
end
w("")
----------------------------------------------------------------------------
-- struct / alias / callback annotations
----------------------------------------------------------------------------
for _, def in ipairs(ordered) do
local desc = clean_description(def.description)
if def.kind == "struct" then
if desc then
w("---" .. desc)
end
w("---@class raylib." .. def.name)
for _, f in ipairs(def.fields) do
local fdesc = clean_description(f.description)
local line = "---@field " .. f.name .. " " .. ann_field(f.type)
if fdesc then
line = line .. " " .. fdesc
end
w(line)
end
else
local pt = parse_type(def.target)
if pt.ptr > 0 then
w("---@alias raylib." .. def.name .. " ffi.cdata*")
else
w("---@alias raylib." .. def.name .. " raylib." .. pt.base)
end
end
w("")
end
for _, cb in ipairs({ CALLBACKS.AudioCallback, CALLBACKS.LoadFileDataCallback,
CALLBACKS.SaveFileDataCallback, CALLBACKS.LoadFileTextCallback,
CALLBACKS.SaveFileTextCallback }) do
if cb then
local parts = {}
for _, p in ipairs(params_of(cb)) do
local pt = parse_type(p.type)
local ann
if pt.base == "char" and pt.ptr == 1 then
ann = "string"
elseif pt.base == "void" and pt.ptr == 1 then
ann = "ffi.cdata*"
else
ann = ann_value(pt.base)
end
parts[#parts + 1] = (p.name or "arg") .. ": " .. ann
end
local ret = parse_type(cb.returnType)
local ret_ann = ""
if ret.base ~= "void" then
if ret.base == "char" and ret.ptr == 1 then
ret_ann = ": string"
else
ret_ann = ": " .. ann_return(cb.returnType)
end
end
w("---@alias raylib." .. cb.name .. " fun(" .. table.concat(parts, ", ") .. ")" .. ret_ann)
w("")
end
end
----------------------------------------------------------------------------
-- wrappers
----------------------------------------------------------------------------
local LUA_KEYWORDS = {
["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true,
["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true,
["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true,
["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true,
["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true,
["while"] = true,
}
local function lua_name(name)
if LUA_KEYWORDS[name] then
return name .. "_"
end
return name
end
local RET_OWNER = {
LoadFileText = "UnloadFileText",
LoadUTF8 = "UnloadUTF8",
EncodeDataBase64 = "MemFree",
TextReplaceAlloc = "MemFree",
TextReplaceBetweenAlloc = "MemFree",
TextInsertAlloc = "MemFree",
}
local SPECIAL = {
TextFormat = true,
TraceLog = true,
CodepointToUTF8 = true,
}
local emitted_wrappers = 0
local function emit_special(f)
if f.name == "TextFormat" then
w("---" .. (clean_description(f.description) or "Text formatting"))
w("---@param fmt string")
w("---@param ... any")
w("---@return string")
w("function M.TextFormat(fmt, ...)")
w(' if select("#", ...) == 0 then')
w(" return fmt")
w(" end")
w(" return string_format(fmt, ...)")
w("end")
w("")
elseif f.name == "TraceLog" then
w("---" .. (clean_description(f.description) or "Show trace log messages"))
w("---@param level integer")
w("---@param fmt string")
w("---@param ... any")
w("---@return nil")
w("function M.TraceLog(level, fmt, ...)")
w(' if select("#", ...) == 0 then')
w(' C.TraceLog(level, "%s", fmt)')
w(" else")
w(' C.TraceLog(level, "%s", string_format(fmt, ...))')
w(" end")
w("end")
w("")
elseif f.name == "CodepointToUTF8" then
w("---" .. (clean_description(f.description) or "Encode a codepoint"))
w("---@param codepoint integer")
w("---@return string|nil")
w("function M.CodepointToUTF8(codepoint)")
w(' local size = ffi.new("int[1]")')
w(" local p = C.CodepointToUTF8(codepoint, size)")
w(" if p == nil then return nil end")
w(" return ffi_string(p, size[0])")
w("end")
w("")
end
emitted_wrappers = emitted_wrappers + 1
end
local function emit_function(f)
local params = params_of(f)
local outs = out_params(f)
local sig = {}
local pre = {}
local args = {}
local arg_ann = {}
local out_vars = {}
local out_ann = {}
for i, p in ipairs(params) do
local pt = parse_type(p.type)
local name = lua_name(p.name)
if pt.base == "..." then
sig[#sig + 1] = "..."
args[#args + 1] = "..."
arg_ann[#arg_ann + 1] = "---@param ... any"
elseif outs[i] then
local var = "_o" .. i
if outs[i] == "inout" then
pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]", ' .. name .. ')'
arg_ann[#arg_ann + 1] = "---@param " .. name .. " raylib." .. pt.base
else
pre[#pre + 1] = 'local ' .. var .. ' = ffi.new("' .. pt.base .. '[1]")'
pre[#pre + 1] = "if " .. name .. " ~= nil then " .. var .. "[0] = " .. name .. " end"
arg_ann[#arg_ann + 1] = "---@param " .. name .. "? raylib." .. pt.base
end
args[#args + 1] = var
out_vars[#out_vars + 1] = var .. "[0]"
out_ann[#out_ann + 1] = "---@return raylib." .. pt.base
sig[#sig + 1] = name
else
sig[#sig + 1] = name
arg_ann[#arg_ann + 1] = "---@param " .. name .. " " .. ann_param(p, false)
if CALLBACKS[pt.base] then
local var = "_cb" .. i
pre[#pre + 1] = "local " .. var .. ' = pin("' .. pt.base .. '", ' .. name .. ")"
args[#args + 1] = var
else
local conv = conversion_for(name, p.type, i)
if conv then
for _, line in ipairs(conv.lines) do
pre[#pre + 1] = line
end
args[#args + 1] = conv.arg
else
args[#args + 1] = name
end
end
end
end
local desc = clean_description(f.description)
if desc then
w("---" .. desc)
end
for _, line in ipairs(arg_ann) do
w(line)
end
if #out_vars > 0 then
for _, line in ipairs(out_ann) do
w(line)
end
elseif parse_type(f.returnType).base == "void" and parse_type(f.returnType).ptr == 0 then
w("---@return nil")
else
w("---@return " .. ann_return(f.returnType))
end
w("function M." .. f.name .. "(" .. table.concat(sig, ", ") .. ")")
for _, line in ipairs(pre) do
w(" " .. line)
end
local call = "C." .. f.name .. "(" .. table.concat(args, ", ") .. ")"
local ret = parse_type(f.returnType)
if #out_vars > 0 then
w(" " .. call)
w(" return " .. table.concat(out_vars, ", "))
elseif ret.base == "void" and ret.ptr == 0 then
w(" " .. call)
elseif ret.base == "char" and ret.ptr == 1 then
local owner = RET_OWNER[f.name]
w(" local _p = " .. call)
w(" if _p == nil then")
w(" return nil")
w(" end")
w(" local _s = ffi_string(_p)")
if owner then
w(" C." .. owner .. "(_p)")
end
w(" return _s")
else
w(" return " .. call)
end
w("end")
w("")
emitted_wrappers = emitted_wrappers + 1
end
for _, f in ipairs(FUNCS) do
if not is_skipped(f) then
if SPECIAL[f.name] then
emit_special(f)
else
emit_function(f)
end
end
end
w("return M")
----------------------------------------------------------------------------
-- write
----------------------------------------------------------------------------
local text = table.concat(out, "\n") .. "\n"
local file, err = io.open(OUT, "wb")
if not file then
die("cannot write %s: %s", OUT, err)
end
file:write(text)
file:close()
local n_struct, n_alias, n_cb = 0, 0, 0
for _, d in ipairs(ordered) do
if d.kind == "struct" then
n_struct = n_struct + 1
else
n_alias = n_alias + 1
end
end
for _ in pairs(CALLBACKS) do
n_cb = n_cb + 1
end
io.stderr:write(string.format(
"gen-hate-no-d: wrote %s (%d functions, %d structs, %d aliases, %d callbacks, %d lines)\n",
OUT, emitted_wrappers, n_struct, n_alias, n_cb, #out))