vt: add ghostty_type_json for struct layout metadata

Add a new C API function that returns a comptime-generated JSON string
describing the size, alignment, and field layout of every C API extern
struct. This lets FFI consumers (particularly WASM) construct structs
by byte offset without hardcoding platform-specific layout.

The JSON is built at comptime using std.json.Stringify via a
StructInfo type that holds per-struct metadata and implements
jsonStringify. A StaticStringMap keyed by C struct name provides
lookup by name as well as iteration for the JSON serialization.

The function is declared in types.h alongside the other common types
and exported as ghostty_type_json.
This commit is contained in:
Mitchell Hashimoto
2026-03-30 08:48:52 -07:00
parent 8fab3ac3f3
commit 2e827cc39d
4 changed files with 256 additions and 1 deletions

View File

@@ -83,4 +83,42 @@ typedef struct {
#define GHOSTTY_INIT_SIZED(type) \
((type){ .size = sizeof(type) })
/**
* Return a pointer to a JSON string describing the layout of every
* C API struct for the current target.
*
* This is primarily useful for language bindings that can't easily
* set C struct fields and need to do so via byte offsets. For example,
* WebAssembly modules can't share struct definitions with the host.
*
* Example (abbreviated):
* @code{.json}
* {
* "GhosttyMouseEncoderSize": {
* "size": 40,
* "align": 8,
* "fields": {
* "size": { "offset": 0, "size": 8, "type": "u64" },
* "screen_width": { "offset": 8, "size": 4, "type": "u32" },
* "screen_height": { "offset": 12, "size": 4, "type": "u32" },
* "cell_width": { "offset": 16, "size": 4, "type": "u32" },
* "cell_height": { "offset": 20, "size": 4, "type": "u32" },
* "padding_top": { "offset": 24, "size": 4, "type": "u32" },
* "padding_bottom": { "offset": 28, "size": 4, "type": "u32" },
* "padding_right": { "offset": 32, "size": 4, "type": "u32" },
* "padding_left": { "offset": 36, "size": 4, "type": "u32" }
* }
* }
* }
* @endcode
*
* The returned pointer is valid for the lifetime of the process.
* The length of the string (excluding any null terminator) is
* written to @p len.
*
* @param[out] len Receives the length of the returned string in bytes.
* @return Pointer to the JSON string.
*/
const char *ghostty_type_json(size_t *len);
#endif /* GHOSTTY_VT_TYPES_H */