gen_zig.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. #-------------------------------------------------------------------------------
  2. # Generate Zig bindings.
  3. #
  4. # Zig coding style:
  5. # - types are PascalCase
  6. # - functions are camelCase
  7. # - otherwise snake_case
  8. #-------------------------------------------------------------------------------
  9. import gen_ir
  10. import os, shutil, sys
  11. import gen_util as util
  12. module_names = {
  13. 'slog_': 'log',
  14. 'sg_': 'gfx',
  15. 'sapp_': 'app',
  16. 'stm_': 'time',
  17. 'saudio_': 'audio',
  18. 'sgl_': 'gl',
  19. 'sdtx_': 'debugtext',
  20. 'sshape_': 'shape',
  21. }
  22. c_source_paths = {
  23. 'slog_': 'sokol-zig/src/sokol/c/sokol_log.c',
  24. 'sg_': 'sokol-zig/src/sokol/c/sokol_gfx.c',
  25. 'sapp_': 'sokol-zig/src/sokol/c/sokol_app.c',
  26. 'stm_': 'sokol-zig/src/sokol/c/sokol_time.c',
  27. 'saudio_': 'sokol-zig/src/sokol/c/sokol_audio.c',
  28. 'sgl_': 'sokol-zig/src/sokol/c/sokol_gl.c',
  29. 'sdtx_': 'sokol-zig/src/sokol/c/sokol_debugtext.c',
  30. 'sshape_': 'sokol-zig/src/sokol/c/sokol_shape.c',
  31. }
  32. ignores = [
  33. 'sdtx_printf',
  34. 'sdtx_vprintf',
  35. 'sg_install_trace_hooks',
  36. 'sg_trace_hooks',
  37. ]
  38. # functions that need to be exposed as 'raw' C callbacks without a Zig wrapper function
  39. c_callbacks = [
  40. 'slog_func'
  41. ]
  42. # NOTE: syntax for function results: "func_name.RESULT"
  43. overrides = {
  44. 'sgl_error': 'sgl_get_error', # 'error' is reserved in Zig
  45. 'sgl_deg': 'sgl_as_degrees',
  46. 'sgl_rad': 'sgl_as_radians',
  47. 'sg_context_desc.color_format': 'int',
  48. 'sg_context_desc.depth_format': 'int',
  49. 'sg_apply_uniforms.ub_index': 'uint32_t',
  50. 'sg_draw.base_element': 'uint32_t',
  51. 'sg_draw.num_elements': 'uint32_t',
  52. 'sg_draw.num_instances': 'uint32_t',
  53. 'sshape_element_range_t.base_element': 'uint32_t',
  54. 'sshape_element_range_t.num_elements': 'uint32_t',
  55. 'sdtx_font.font_index': 'uint32_t',
  56. 'SGL_NO_ERROR': 'SGL_ERROR_NO_ERROR',
  57. }
  58. prim_types = {
  59. 'int': 'i32',
  60. 'bool': 'bool',
  61. 'char': 'u8',
  62. 'int8_t': 'i8',
  63. 'uint8_t': 'u8',
  64. 'int16_t': 'i16',
  65. 'uint16_t': 'u16',
  66. 'int32_t': 'i32',
  67. 'uint32_t': 'u32',
  68. 'int64_t': 'i64',
  69. 'uint64_t': 'u64',
  70. 'float': 'f32',
  71. 'double': 'f64',
  72. 'uintptr_t': 'usize',
  73. 'intptr_t': 'isize',
  74. 'size_t': 'usize'
  75. }
  76. prim_defaults = {
  77. 'int': '0',
  78. 'bool': 'false',
  79. 'int8_t': '0',
  80. 'uint8_t': '0',
  81. 'int16_t': '0',
  82. 'uint16_t': '0',
  83. 'int32_t': '0',
  84. 'uint32_t': '0',
  85. 'int64_t': '0',
  86. 'uint64_t': '0',
  87. 'float': '0.0',
  88. 'double': '0.0',
  89. 'uintptr_t': '0',
  90. 'intptr_t': '0',
  91. 'size_t': '0'
  92. }
  93. struct_types = []
  94. enum_types = []
  95. enum_items = {}
  96. out_lines = ''
  97. def reset_globals():
  98. global struct_types
  99. global enum_types
  100. global enum_items
  101. global out_lines
  102. struct_types = []
  103. enum_types = []
  104. enum_items = {}
  105. out_lines = ''
  106. def l(s):
  107. global out_lines
  108. out_lines += s + '\n'
  109. def as_zig_prim_type(s):
  110. return prim_types[s]
  111. # prefix_bla_blub(_t) => (dep.)BlaBlub
  112. def as_zig_struct_type(s, prefix):
  113. parts = s.lower().split('_')
  114. outp = '' if s.startswith(prefix) else f'{parts[0]}.'
  115. for part in parts[1:]:
  116. # ignore '_t' type postfix
  117. if (part != 't'):
  118. outp += part.capitalize()
  119. return outp
  120. # prefix_bla_blub(_t) => (dep.)BlaBlub
  121. def as_zig_enum_type(s, prefix):
  122. parts = s.lower().split('_')
  123. outp = '' if s.startswith(prefix) else f'{parts[0]}.'
  124. for part in parts[1:]:
  125. if (part != 't'):
  126. outp += part.capitalize()
  127. return outp
  128. def check_override(name, default=None):
  129. if name in overrides:
  130. return overrides[name]
  131. elif default is None:
  132. return name
  133. else:
  134. return default
  135. def check_ignore(name):
  136. return name in ignores
  137. # PREFIX_ENUM_BLA => Bla, _PREFIX_ENUM_BLA => Bla
  138. def as_enum_item_name(s):
  139. outp = s.lstrip('_')
  140. parts = outp.split('_')[2:]
  141. outp = '_'.join(parts)
  142. if outp[0].isdigit():
  143. outp = '_' + outp
  144. return outp
  145. def enum_default_item(enum_name):
  146. return enum_items[enum_name][0]
  147. def is_prim_type(s):
  148. return s in prim_types
  149. def is_struct_type(s):
  150. return s in struct_types
  151. def is_enum_type(s):
  152. return s in enum_types
  153. def is_const_prim_ptr(s):
  154. for prim_type in prim_types:
  155. if s == f"const {prim_type} *":
  156. return True
  157. return False
  158. def is_prim_ptr(s):
  159. for prim_type in prim_types:
  160. if s == f"{prim_type} *":
  161. return True
  162. return False
  163. def is_const_struct_ptr(s):
  164. for struct_type in struct_types:
  165. if s == f"const {struct_type} *":
  166. return True
  167. return False
  168. def type_default_value(s):
  169. return prim_defaults[s]
  170. def as_c_arg_type(arg_type, prefix):
  171. if arg_type == "void":
  172. return "void"
  173. elif is_prim_type(arg_type):
  174. return as_zig_prim_type(arg_type)
  175. elif is_struct_type(arg_type):
  176. return as_zig_struct_type(arg_type, prefix)
  177. elif is_enum_type(arg_type):
  178. return as_zig_enum_type(arg_type, prefix)
  179. elif util.is_void_ptr(arg_type):
  180. return "?*anyopaque"
  181. elif util.is_const_void_ptr(arg_type):
  182. return "?*const anyopaque"
  183. elif util.is_string_ptr(arg_type):
  184. return "[*c]const u8"
  185. elif is_const_struct_ptr(arg_type):
  186. return f"[*c]const {as_zig_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  187. elif is_prim_ptr(arg_type):
  188. return f"[*c] {as_zig_prim_type(util.extract_ptr_type(arg_type))}"
  189. elif is_const_prim_ptr(arg_type):
  190. return f"[*c]const {as_zig_prim_type(util.extract_ptr_type(arg_type))}"
  191. else:
  192. sys.exit(f"Error as_c_arg_type(): {arg_type}")
  193. def as_zig_arg_type(arg_prefix, arg_type, prefix):
  194. # NOTE: if arg_prefix is None, the result is used as return value
  195. pre = "" if arg_prefix is None else arg_prefix
  196. if arg_type == "void":
  197. if arg_prefix is None:
  198. return "void"
  199. else:
  200. return ""
  201. elif is_prim_type(arg_type):
  202. return pre + as_zig_prim_type(arg_type)
  203. elif is_struct_type(arg_type):
  204. return pre + as_zig_struct_type(arg_type, prefix)
  205. elif is_enum_type(arg_type):
  206. return pre + as_zig_enum_type(arg_type, prefix)
  207. elif util.is_void_ptr(arg_type):
  208. return pre + "?*anyopaque"
  209. elif util.is_const_void_ptr(arg_type):
  210. return pre + "?*const anyopaque"
  211. elif util.is_string_ptr(arg_type):
  212. return pre + "[:0]const u8"
  213. elif is_const_struct_ptr(arg_type):
  214. # not a bug, pass const structs by value
  215. return pre + f"{as_zig_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  216. elif is_prim_ptr(arg_type):
  217. return pre + f"* {as_zig_prim_type(util.extract_ptr_type(arg_type))}"
  218. elif is_const_prim_ptr(arg_type):
  219. return pre + f"*const {as_zig_prim_type(util.extract_ptr_type(arg_type))}"
  220. else:
  221. sys.exit(f"ERROR as_zig_arg_type(): {arg_type}")
  222. def is_zig_string(zig_type):
  223. return zig_type == "[:0]const u8"
  224. # get C-style arguments of a function pointer as string
  225. def funcptr_args_c(field_type, prefix):
  226. tokens = field_type[field_type.index('(*)')+4:-1].split(',')
  227. s = ""
  228. for token in tokens:
  229. arg_type = token.strip()
  230. if s != "":
  231. s += ", "
  232. c_arg = as_c_arg_type(arg_type, prefix)
  233. if c_arg == "void":
  234. return ""
  235. else:
  236. s += c_arg
  237. return s
  238. # get C-style result of a function pointer as string
  239. def funcptr_result_c(field_type):
  240. res_type = field_type[:field_type.index('(*)')].strip()
  241. if res_type == 'void':
  242. return 'void'
  243. elif util.is_const_void_ptr(res_type):
  244. return '?*const anyopaque'
  245. elif util.is_void_ptr(res_type):
  246. return '?*anyopaque'
  247. else:
  248. sys.exit(f"ERROR funcptr_result_c(): {field_type}")
  249. def funcdecl_args_c(decl, prefix):
  250. s = ""
  251. func_name = decl['name']
  252. for param_decl in decl['params']:
  253. if s != "":
  254. s += ", "
  255. param_name = param_decl['name']
  256. param_type = check_override(f'{func_name}.{param_name}', default=param_decl['type'])
  257. s += as_c_arg_type(param_type, prefix)
  258. return s
  259. def funcdecl_args_zig(decl, prefix):
  260. s = ""
  261. func_name = decl['name']
  262. for param_decl in decl['params']:
  263. if s != "":
  264. s += ", "
  265. param_name = param_decl['name']
  266. param_type = check_override(f'{func_name}.{param_name}', default=param_decl['type'])
  267. s += f"{as_zig_arg_type(f'{param_name}: ', param_type, prefix)}"
  268. return s
  269. def funcdecl_result_c(decl, prefix):
  270. func_name = decl['name']
  271. decl_type = decl['type']
  272. result_type = check_override(f'{func_name}.RESULT', default=decl_type[:decl_type.index('(')].strip())
  273. return as_c_arg_type(result_type, prefix)
  274. def funcdecl_result_zig(decl, prefix):
  275. func_name = decl['name']
  276. decl_type = decl['type']
  277. result_type = check_override(f'{func_name}.RESULT', default=decl_type[:decl_type.index('(')].strip())
  278. zig_res_type = as_zig_arg_type(None, result_type, prefix)
  279. return zig_res_type
  280. def gen_struct(decl, prefix):
  281. struct_name = check_override(decl['name'])
  282. zig_type = as_zig_struct_type(struct_name, prefix)
  283. l(f"pub const {zig_type} = extern struct {{")
  284. for field in decl['fields']:
  285. field_name = check_override(field['name'])
  286. field_type = check_override(f'{struct_name}.{field_name}', default=field['type'])
  287. if is_prim_type(field_type):
  288. l(f" {field_name}: {as_zig_prim_type(field_type)} = {type_default_value(field_type)},")
  289. elif is_struct_type(field_type):
  290. l(f" {field_name}: {as_zig_struct_type(field_type, prefix)} = .{{ }},")
  291. elif is_enum_type(field_type):
  292. l(f" {field_name}: {as_zig_enum_type(field_type, prefix)} = .{enum_default_item(field_type)},")
  293. elif util.is_string_ptr(field_type):
  294. l(f" {field_name}: [*c]const u8 = null,")
  295. elif util.is_const_void_ptr(field_type):
  296. l(f" {field_name}: ?*const anyopaque = null,")
  297. elif util.is_void_ptr(field_type):
  298. l(f" {field_name}: ?*anyopaque = null,")
  299. elif is_const_prim_ptr(field_type):
  300. l(f" {field_name}: ?[*]const {as_zig_prim_type(util.extract_ptr_type(field_type))} = null,")
  301. elif util.is_func_ptr(field_type):
  302. l(f" {field_name}: ?*const fn({funcptr_args_c(field_type, prefix)}) callconv(.C) {funcptr_result_c(field_type)} = null,")
  303. elif util.is_1d_array_type(field_type):
  304. array_type = util.extract_array_type(field_type)
  305. array_sizes = util.extract_array_sizes(field_type)
  306. if is_prim_type(array_type) or is_struct_type(array_type):
  307. if is_prim_type(array_type):
  308. zig_type = as_zig_prim_type(array_type)
  309. def_val = type_default_value(array_type)
  310. elif is_struct_type(array_type):
  311. zig_type = as_zig_struct_type(array_type, prefix)
  312. def_val = '.{}'
  313. elif is_enum_type(array_type):
  314. zig_type = as_zig_enum_type(array_type, prefix)
  315. def_val = '.{}'
  316. else:
  317. sys.exit(f"ERROR gen_struct is_1d_array_type: {array_type}")
  318. t0 = f"[{array_sizes[0]}]{zig_type}"
  319. t1 = f"[_]{zig_type}"
  320. l(f" {field_name}: {t0} = {t1}{{{def_val}}} ** {array_sizes[0]},")
  321. elif util.is_const_void_ptr(array_type):
  322. l(f" {field_name}: [{array_sizes[0]}]?*const anyopaque = [_]?*const anyopaque {{ null }} ** {array_sizes[0]},")
  323. else:
  324. sys.exit(f"ERROR gen_struct: array {field_name}: {field_type} => {array_type} [{array_sizes[0]}]")
  325. elif util.is_2d_array_type(field_type):
  326. array_type = util.extract_array_type(field_type)
  327. array_sizes = util.extract_array_sizes(field_type)
  328. if is_prim_type(array_type):
  329. zig_type = as_zig_prim_type(array_type)
  330. def_val = type_default_value(array_type)
  331. elif is_struct_type(array_type):
  332. zig_type = as_zig_struct_type(array_type, prefix)
  333. def_val = ".{ }"
  334. else:
  335. sys.exit(f"ERROR gen_struct is_2d_array_type: {array_type}")
  336. t0 = f"[{array_sizes[0]}][{array_sizes[1]}]{zig_type}"
  337. l(f" {field_name}: {t0} = [_][{array_sizes[1]}]{zig_type}{{[_]{zig_type}{{ {def_val} }}**{array_sizes[1]}}}**{array_sizes[0]},")
  338. else:
  339. sys.exit(f"ERROR gen_struct: {field_name}: {field_type};")
  340. l("};")
  341. def gen_consts(decl, prefix):
  342. for item in decl['items']:
  343. item_name = check_override(item['name'])
  344. l(f"pub const {util.as_lower_snake_case(item_name, prefix)} = {item['value']};")
  345. def gen_enum(decl, prefix):
  346. enum_name = check_override(decl['name'])
  347. l(f"pub const {as_zig_enum_type(enum_name, prefix)} = enum(i32) {{")
  348. for item in decl['items']:
  349. item_name = as_enum_item_name(check_override(item['name']))
  350. if item_name != "FORCE_U32":
  351. if 'value' in item:
  352. l(f" {item_name} = {item['value']},")
  353. else:
  354. l(f" {item_name},")
  355. l("};")
  356. def gen_func_c(decl, prefix):
  357. l(f"pub extern fn {decl['name']}({funcdecl_args_c(decl, prefix)}) {funcdecl_result_c(decl, prefix)};")
  358. def gen_func_zig(decl, prefix):
  359. c_func_name = decl['name']
  360. zig_func_name = util.as_lower_camel_case(check_override(decl['name']), prefix)
  361. if c_func_name in c_callbacks:
  362. # a simple forwarded C callback function
  363. l(f"pub const {zig_func_name} = {c_func_name};")
  364. else:
  365. zig_res_type = funcdecl_result_zig(decl, prefix)
  366. l(f"pub fn {zig_func_name}({funcdecl_args_zig(decl, prefix)}) {zig_res_type} {{")
  367. if is_zig_string(zig_res_type):
  368. # special case: convert C string to Zig string slice
  369. s = f" return cStrToZig({c_func_name}("
  370. elif zig_res_type != 'void':
  371. s = f" return {c_func_name}("
  372. else:
  373. s = f" {c_func_name}("
  374. for i, param_decl in enumerate(decl['params']):
  375. if i > 0:
  376. s += ", "
  377. arg_name = param_decl['name']
  378. arg_type = param_decl['type']
  379. if is_const_struct_ptr(arg_type):
  380. s += f"&{arg_name}"
  381. elif util.is_string_ptr(arg_type):
  382. s += f"@ptrCast([*c]const u8,{arg_name})"
  383. else:
  384. s += arg_name
  385. if is_zig_string(zig_res_type):
  386. s += ")"
  387. s += ");"
  388. l(s)
  389. l("}")
  390. def pre_parse(inp):
  391. global struct_types
  392. global enum_types
  393. for decl in inp['decls']:
  394. kind = decl['kind']
  395. if kind == 'struct':
  396. struct_types.append(decl['name'])
  397. elif kind == 'enum':
  398. enum_name = decl['name']
  399. enum_types.append(enum_name)
  400. enum_items[enum_name] = []
  401. for item in decl['items']:
  402. enum_items[enum_name].append(as_enum_item_name(item['name']))
  403. def gen_imports(inp, dep_prefixes):
  404. l('const builtin = @import("builtin");')
  405. for dep_prefix in dep_prefixes:
  406. dep_module_name = module_names[dep_prefix]
  407. l(f'const {dep_prefix[:-1]} = @import("{dep_module_name}.zig");')
  408. l('')
  409. def gen_helpers(inp):
  410. l('// helper function to convert a C string to a Zig string slice')
  411. l('fn cStrToZig(c_str: [*c]const u8) [:0]const u8 {')
  412. l(' return @import("std").mem.span(c_str);')
  413. l('}')
  414. if inp['prefix'] in ['sg_', 'sdtx_', 'sshape_']:
  415. l('// helper function to convert "anything" to a Range struct')
  416. l('pub fn asRange(val: anytype) Range {')
  417. l(' const type_info = @typeInfo(@TypeOf(val));')
  418. l(' switch (type_info) {')
  419. l(' .Pointer => {')
  420. l(' switch (type_info.Pointer.size) {')
  421. l(' .One => return .{ .ptr = val, .size = @sizeOf(type_info.Pointer.child) },')
  422. l(' .Slice => return .{ .ptr = val.ptr, .size = @sizeOf(type_info.Pointer.child) * val.len },')
  423. l(' else => @compileError("FIXME: Pointer type!"),')
  424. l(' }')
  425. l(' },')
  426. l(' .Struct, .Array => {')
  427. l(' @compileError("Structs and arrays must be passed as pointers to asRange");')
  428. l(' },')
  429. l(' else => {')
  430. l(' @compileError("Cannot convert to range!");')
  431. l(' }')
  432. l(' }')
  433. l('}')
  434. l('')
  435. if inp['prefix'] == 'sdtx_':
  436. l('// std.fmt compatible Writer')
  437. l('pub const Writer = struct {')
  438. l(' pub const Error = error { };')
  439. l(' pub fn writeAll(self: Writer, bytes: []const u8) Error!void {')
  440. l(' _ = self;')
  441. l(' for (bytes) |byte| {')
  442. l(' putc(byte);')
  443. l(' }')
  444. l(' }')
  445. l(' pub fn writeByteNTimes(self: Writer, byte: u8, n: u64) Error!void {')
  446. l(' _ = self;')
  447. l(' var i: u64 = 0;')
  448. l(' while (i < n): (i += 1) {')
  449. l(' putc(byte);')
  450. l(' }')
  451. l(' }')
  452. l('};')
  453. l('// std.fmt-style formatted print')
  454. l('pub fn print(comptime fmt: anytype, args: anytype) void {')
  455. l(' var writer: Writer = .{};')
  456. l(' @import("std").fmt.format(writer, fmt, args) catch {};')
  457. l('}')
  458. l('')
  459. def gen_module(inp, dep_prefixes):
  460. l('// machine generated, do not edit')
  461. l('')
  462. gen_imports(inp, dep_prefixes)
  463. gen_helpers(inp)
  464. pre_parse(inp)
  465. prefix = inp['prefix']
  466. for decl in inp['decls']:
  467. if not decl['is_dep']:
  468. kind = decl['kind']
  469. if kind == 'consts':
  470. gen_consts(decl, prefix)
  471. elif not check_ignore(decl['name']):
  472. if kind == 'struct':
  473. gen_struct(decl, prefix)
  474. elif kind == 'enum':
  475. gen_enum(decl, prefix)
  476. elif kind == 'func':
  477. gen_func_c(decl, prefix)
  478. gen_func_zig(decl, prefix)
  479. def prepare():
  480. print('=== Generating Zig bindings:')
  481. if not os.path.isdir('sokol-zig/src/sokol'):
  482. os.makedirs('sokol-zig/src/sokol')
  483. if not os.path.isdir('sokol-zig/src/sokol/c'):
  484. os.makedirs('sokol-zig/src/sokol/c')
  485. def gen(c_header_path, c_prefix, dep_c_prefixes):
  486. if not c_prefix in module_names:
  487. print(f' >> warning: skipping generation for {c_prefix} prefix...')
  488. return
  489. module_name = module_names[c_prefix]
  490. c_source_path = c_source_paths[c_prefix]
  491. print(f' {c_header_path} => {module_name}')
  492. reset_globals()
  493. shutil.copyfile(c_header_path, f'sokol-zig/src/sokol/c/{os.path.basename(c_header_path)}')
  494. ir = gen_ir.gen(c_header_path, c_source_path, module_name, c_prefix, dep_c_prefixes)
  495. gen_module(ir, dep_c_prefixes)
  496. output_path = f"sokol-zig/src/sokol/{ir['module']}.zig"
  497. with open(output_path, 'w', newline='\n') as f_outp:
  498. f_outp.write(out_lines)