gen_rust.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. # -------------------------------------------------------------------------------
  2. # Generate rust bindings.
  3. #
  4. # rust coding style:
  5. # - types are PascalCase
  6. # - otherwise snake_case
  7. # -------------------------------------------------------------------------------
  8. import gen_ir
  9. import os, shutil, sys
  10. import gen_util as util
  11. module_names = {
  12. "slog_": "log",
  13. "sg_": "gfx",
  14. "sapp_": "app",
  15. "stm_": "time",
  16. "saudio_": "audio",
  17. "sgl_": "gl",
  18. "sdtx_": "debugtext",
  19. "sshape_": "shape",
  20. "sapp_sg": "glue",
  21. "simgui_": "imgui",
  22. "sg_imgui_": "gfx_imgui",
  23. }
  24. module_requires_rust_feature = {
  25. module_names["simgui_"]: "imgui",
  26. module_names["sg_imgui_"]: "imgui",
  27. }
  28. c_source_paths = {
  29. "slog_": "sokol-rust/src/sokol/c/sokol_log.c",
  30. "sg_": "sokol-rust/src/sokol/c/sokol_gfx.c",
  31. "sapp_": "sokol-rust/src/sokol/c/sokol_app.c",
  32. "stm_": "sokol-rust/src/sokol/c/sokol_time.c",
  33. "saudio_": "sokol-rust/src/sokol/c/sokol_audio.c",
  34. "sgl_": "sokol-rust/src/sokol/c/sokol_gl.c",
  35. "sdtx_": "sokol-rust/src/sokol/c/sokol_debugtext.c",
  36. "sshape_": "sokol-rust/src/sokol/c/sokol_shape.c",
  37. "sapp_sg": "sokol-rust/src/sokol/c/sokol_glue.c",
  38. "simgui_": "sokol-rust/src/sokol/c/sokol_imgui.c",
  39. "sg_imgui_": "sokol-rust/src/sokol/c/sokol_gfx_imgui.c",
  40. }
  41. ignores = [
  42. "sdtx_printf",
  43. "sdtx_vprintf",
  44. # "sg_install_trace_hooks",
  45. # "sg_trace_hooks",
  46. ]
  47. range_struct_name = "Range"
  48. # functions that need to be exposed as 'raw' C callbacks without a rust wrapper function
  49. c_callbacks = ["slog_func"]
  50. # NOTE: syntax for function results: "func_name.RESULT"
  51. overrides = {
  52. "type": "_type",
  53. "ref": "_ref",
  54. "sg_apply_uniforms.ub_index": "uintptr_t",
  55. "sg_draw.base_element": "uintptr_t",
  56. "sg_draw.num_elements": "uintptr_t",
  57. "sg_draw.num_instances": "uintptr_t",
  58. "sshape_element_range_t.base_element": "uintptr_t",
  59. "sshape_element_range_t.num_elements": "uintptr_t",
  60. "sdtx_font.font_index": "uintptr_t",
  61. "sdtx_move": "sdtx_move_cursor",
  62. "sdtx_move_x": "sdtx_move_cursor_x",
  63. "sdtx_move_y": "sdtx_move_cursor_y",
  64. "sg_image_type::SG_IMAGETYPE_2D": "SG_IMAGEYPE_DIM2",
  65. "sg_image_type::SG_IMAGETYPE_3D": "SG_IMAGETYPE_DIM3",
  66. "sapp_keycode::SAPP_KEYCODE_0": "SAPP_KEYCODE_NUM0",
  67. "sapp_keycode::SAPP_KEYCODE_1": "SAPP_KEYCODE_NUM1",
  68. "sapp_keycode::SAPP_KEYCODE_2": "SAPP_KEYCODE_NUM2",
  69. "sapp_keycode::SAPP_KEYCODE_3": "SAPP_KEYCODE_NUM3",
  70. "sapp_keycode::SAPP_KEYCODE_4": "SAPP_KEYCODE_NUM4",
  71. "sapp_keycode::SAPP_KEYCODE_5": "SAPP_KEYCODE_NUM5",
  72. "sapp_keycode::SAPP_KEYCODE_6": "SAPP_KEYCODE_NUM6",
  73. "sapp_keycode::SAPP_KEYCODE_7": "SAPP_KEYCODE_NUM7",
  74. "sapp_keycode::SAPP_KEYCODE_8": "SAPP_KEYCODE_NUM8",
  75. "sapp_keycode::SAPP_KEYCODE_9": "SAPP_KEYCODE_NUM9",
  76. # "sgl_error": "sgl_get_error", # 'error' is reserved in zig
  77. # "sgl_deg": "sgl_as_degrees",
  78. # "sgl_rad": "sgl_as_radians",
  79. # "sg_context_desc.color_format": "int",
  80. # "SGL_NO_ERROR": "SGL_ERROR_NO_ERROR",
  81. # "sg_context_desc.depth_format": "int",
  82. }
  83. prim_types = {
  84. "int": "i32",
  85. "bool": "bool",
  86. "char": "core::ffi::c_char",
  87. "int8_t": "i8",
  88. "uint8_t": "u8",
  89. "int16_t": "i16",
  90. "uint16_t": "u16",
  91. "int32_t": "i32",
  92. "uint32_t": "u32",
  93. "int64_t": "i64",
  94. "uint64_t": "u64",
  95. "float": "f32",
  96. "double": "f64",
  97. "uintptr_t": "usize",
  98. "intptr_t": "isize",
  99. "size_t": "usize",
  100. }
  101. prim_defaults = {
  102. "int": "0",
  103. "bool": "false",
  104. "int8_t": "0",
  105. "uint8_t": "0",
  106. "int16_t": "0",
  107. "uint16_t": "0",
  108. "int32_t": "0",
  109. "uint32_t": "0",
  110. "int64_t": "0",
  111. "uint64_t": "0",
  112. "float": "0.0",
  113. "double": "0.0",
  114. "uintptr_t": "0",
  115. "intptr_t": "0",
  116. "size_t": "0",
  117. "char": "0",
  118. }
  119. special_constant_types = {
  120. "SG_INVALID_ID": "u32"
  121. }
  122. struct_types = []
  123. enum_types = []
  124. enum_items = {}
  125. out_lines = ""
  126. def reset_globals():
  127. global struct_types
  128. global enum_types
  129. global enum_items
  130. global out_lines
  131. struct_types = []
  132. enum_types = []
  133. enum_items = {}
  134. out_lines = ""
  135. def l(s):
  136. global out_lines
  137. out_lines += s + "\n"
  138. def as_rust_prim_type(s):
  139. return prim_types[s]
  140. def as_upper_snake_case(s, prefix):
  141. outp = s.lower()
  142. if outp.startswith(prefix):
  143. outp = outp[len(prefix):]
  144. return outp.upper()
  145. # prefix_bla_blub(_t) => (dep::)BlaBlub
  146. def as_rust_struct_type(s, prefix):
  147. parts = s.lower().split("_")
  148. outp = "" if s.startswith(prefix) else f"{parts[0]}::"
  149. for part in parts[1:]:
  150. # ignore '_t' type postfix
  151. if part != "t":
  152. outp += part.capitalize()
  153. return outp
  154. # prefix_bla_blub(_t) => (dep::)BlaBlub
  155. def as_rust_enum_type(s, prefix):
  156. parts = s.lower().split("_")
  157. outp = "" if s.startswith(prefix) else f"{parts[0]}::"
  158. for part in parts[1:]:
  159. # ignore '_t' type postfix
  160. if part != "t":
  161. outp += part.capitalize()
  162. return outp
  163. def check_override(name, default=None):
  164. if name in overrides:
  165. return overrides[name]
  166. elif default is None:
  167. return name
  168. else:
  169. return default
  170. def check_ignore(name):
  171. return name in ignores
  172. # PREFIX_ENUM_BLA_BLA => BlaBla, _PREFIX_ENUM_BLA_BLA => BlaBla
  173. def as_enum_item_name(s):
  174. parts = s.lstrip("_").split("_")
  175. outp = ""
  176. for i, part in enumerate(parts[2:]):
  177. # TODO: What to do with enum fields starting with numbers?
  178. outp += part.capitalize()
  179. return outp
  180. def enum_default_item(enum_name):
  181. return enum_items[enum_name][0]
  182. def is_prim_type(s):
  183. return s in prim_types
  184. def is_struct_type(s):
  185. return s in struct_types
  186. def is_enum_type(s):
  187. return s in enum_types
  188. def is_const_prim_ptr(s):
  189. for prim_type in prim_types:
  190. if s == f"const {prim_type} *":
  191. return True
  192. return False
  193. def is_prim_ptr(s):
  194. for prim_type in prim_types:
  195. if s == f"{prim_type} *":
  196. return True
  197. return False
  198. def is_const_struct_ptr(s):
  199. for struct_type in struct_types:
  200. if s == f"const {struct_type} *":
  201. return True
  202. return False
  203. def is_struct_ptr(s):
  204. for struct_type in struct_types:
  205. if s == f"{struct_type} *":
  206. return True
  207. return False
  208. def type_default_value(s):
  209. return prim_defaults[s]
  210. def as_c_arg_type(arg_prefix, arg_type, prefix):
  211. # NOTE: if arg_prefix is None, the result is used as return value
  212. pre = "" if arg_prefix is None else arg_prefix
  213. if arg_type == "void":
  214. return ""
  215. elif is_prim_type(arg_type):
  216. return pre + as_rust_prim_type(arg_type)
  217. elif is_struct_type(arg_type):
  218. return pre + as_rust_struct_type(arg_type, prefix)
  219. elif is_enum_type(arg_type):
  220. return pre + as_rust_enum_type(arg_type, prefix)
  221. elif util.is_void_ptr(arg_type):
  222. return pre + "*mut core::ffi::c_void"
  223. elif util.is_const_void_ptr(arg_type):
  224. return pre + "*const core::ffi::c_void"
  225. elif util.is_string_ptr(arg_type):
  226. return pre + "*const core::ffi::c_char"
  227. elif is_const_struct_ptr(arg_type):
  228. return pre + f"*const {as_rust_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  229. elif is_struct_ptr(arg_type):
  230. return pre + f"*mut {as_rust_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  231. elif is_prim_ptr(arg_type):
  232. return pre + f"*mut {as_rust_prim_type(util.extract_ptr_type(arg_type))}"
  233. elif is_const_prim_ptr(arg_type):
  234. return pre + f"*const {as_rust_prim_type(util.extract_ptr_type(arg_type))}"
  235. else:
  236. sys.exit(f"ERROR as_c_arg_type(): {arg_type}")
  237. def as_rust_arg_type(arg_prefix, arg_type, prefix):
  238. # NOTE: if arg_prefix is None, the result is used as return value
  239. pre = "" if arg_prefix is None else arg_prefix
  240. if arg_type == "void":
  241. return ""
  242. elif is_prim_type(arg_type):
  243. return pre + as_rust_prim_type(arg_type)
  244. elif is_struct_type(arg_type):
  245. return pre + as_rust_struct_type(arg_type, prefix)
  246. elif is_enum_type(arg_type):
  247. return pre + as_rust_enum_type(arg_type, prefix)
  248. elif util.is_void_ptr(arg_type):
  249. return pre + "*mut core::ffi::c_void"
  250. elif util.is_const_void_ptr(arg_type):
  251. return pre + "*const core::ffi::c_void"
  252. elif util.is_string_ptr(arg_type):
  253. return pre + "&str"
  254. elif is_const_struct_ptr(arg_type):
  255. return pre + f"&{as_rust_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  256. elif is_struct_ptr(arg_type):
  257. return pre + f"&mut {as_rust_struct_type(util.extract_ptr_type(arg_type), prefix)}"
  258. elif is_prim_ptr(arg_type):
  259. return pre + f"&mut {as_rust_prim_type(util.extract_ptr_type(arg_type))}"
  260. elif is_const_prim_ptr(arg_type):
  261. return pre + f"&{as_rust_prim_type(util.extract_ptr_type(arg_type))}"
  262. else:
  263. sys.exit(f"ERROR as_rust_arg_type(): {arg_type}")
  264. def is_rust_string(rust_type):
  265. return rust_type == "&str" or rust_type == " -> &'static str"
  266. # get C-style arguments of a function pointer as string
  267. def funcptr_args_c(field_type, prefix):
  268. tokens = field_type[field_type.index("(*)") + 4: -1].split(",")
  269. s = ""
  270. for token in tokens:
  271. arg_type = token.strip()
  272. if s != "":
  273. s += ", "
  274. c_arg = as_c_arg_type(None, arg_type, prefix)
  275. if c_arg == "void":
  276. return ""
  277. else:
  278. s += c_arg
  279. return s
  280. # get C-style result of a function pointer as string
  281. def funcptr_result_c(field_type):
  282. res_type = field_type[: field_type.index("(*)")].strip()
  283. if res_type == "void":
  284. return ""
  285. elif util.is_const_void_ptr(res_type):
  286. return " -> *const core::ffi::c_void"
  287. elif util.is_void_ptr(res_type):
  288. return " -> *mut core::ffi::c_void"
  289. else:
  290. sys.exit(f"ERROR funcptr_result_c(): {field_type}")
  291. def funcdecl_args_c(decl, prefix):
  292. s = ""
  293. func_name = decl["name"]
  294. for param_decl in decl["params"]:
  295. if s != "":
  296. s += ", "
  297. param_name = param_decl["name"]
  298. param_type = check_override(
  299. f"{func_name}.{param_name}", default=param_decl["type"]
  300. )
  301. s += f"{as_c_arg_type(f'{param_name}: ', param_type, prefix)}"
  302. return s
  303. def funcdecl_args_rust(decl, prefix):
  304. s = ""
  305. func_name = decl["name"]
  306. for param_decl in decl["params"]:
  307. if s != "":
  308. s += ", "
  309. param_name = param_decl["name"]
  310. param_type = check_override(
  311. f"{func_name}.{param_name}", default=param_decl["type"]
  312. )
  313. s += f"{as_rust_arg_type(f'{param_name}: ', param_type, prefix)}"
  314. return s
  315. def funcdecl_result_c(decl, prefix):
  316. func_name = decl["name"]
  317. decl_type = decl["type"]
  318. result_type = check_override(
  319. f"{func_name}.RESULT", default=decl_type[: decl_type.index("(")].strip()
  320. )
  321. it = as_c_arg_type(None, result_type, prefix)
  322. if it == "()" or it == "":
  323. return ""
  324. else:
  325. return f" -> {it}"
  326. def funcdecl_result_rust(decl, prefix):
  327. func_name = decl["name"]
  328. decl_type = decl["type"]
  329. result_type = check_override(
  330. f"{func_name}.RESULT", default=decl_type[: decl_type.index("(")].strip()
  331. )
  332. rust_res_type = as_rust_arg_type(None, result_type, prefix)
  333. if is_rust_string(rust_res_type):
  334. rust_res_type = "&'static str"
  335. if rust_res_type == "":
  336. return ""
  337. else:
  338. return f" -> {rust_res_type }"
  339. def gen_struct(decl, prefix):
  340. struct_name = check_override(decl["name"])
  341. rust_type = as_rust_struct_type(struct_name, prefix)
  342. rust_struct_type = rust_type
  343. struct_lines = []
  344. default_lines = []
  345. for field in decl["fields"]:
  346. field_name = check_override(field["name"])
  347. field_type = check_override(
  348. f"{struct_name}.{field_name}", default=field["type"]
  349. )
  350. if is_prim_type(field_type):
  351. struct_lines.append(
  352. f"pub {field_name}: {as_rust_prim_type(field_type)}"
  353. )
  354. default_lines.append(
  355. f"{field_name}: {type_default_value(field_type)}"
  356. )
  357. elif is_struct_type(field_type):
  358. struct_lines.append(
  359. f"pub {field_name}: {as_rust_struct_type(field_type, prefix)}"
  360. )
  361. default_lines.append(
  362. f"{field_name}: {as_rust_struct_type(field_type, prefix)}::new()"
  363. )
  364. elif is_enum_type(field_type):
  365. struct_lines.append(
  366. f"pub {field_name}: {as_rust_enum_type(field_type, prefix)}"
  367. )
  368. default_lines.append(
  369. f"{field_name}: {as_rust_enum_type(field_type, prefix)}::new()"
  370. )
  371. elif util.is_string_ptr(field_type):
  372. struct_lines.append(
  373. f"pub {field_name}: *const core::ffi::c_char"
  374. )
  375. default_lines.append(
  376. f"{field_name}: core::ptr::null()"
  377. )
  378. elif util.is_const_void_ptr(field_type):
  379. struct_lines.append(
  380. f"pub {field_name}: *const core::ffi::c_void"
  381. )
  382. default_lines.append(
  383. f"{field_name}: core::ptr::null()"
  384. )
  385. elif util.is_void_ptr(field_type):
  386. struct_lines.append(
  387. f"pub {field_name}: *mut core::ffi::c_void"
  388. )
  389. default_lines.append(
  390. f"{field_name}: core::ptr::null_mut()"
  391. )
  392. elif is_const_prim_ptr(field_type):
  393. struct_lines.append(
  394. f"pub {field_name}: *const {as_rust_prim_type(util.extract_ptr_type(field_type))}"
  395. )
  396. default_lines.append(
  397. f"{field_name}: core::ptr::null()"
  398. )
  399. elif is_prim_ptr(field_type):
  400. struct_lines.append(
  401. f"pub {field_name}: *mut {as_rust_prim_type(util.extract_ptr_type(field_type))}"
  402. )
  403. default_lines.append(
  404. f"{field_name}: core::ptr::null_mut()"
  405. )
  406. elif is_const_struct_ptr(field_type):
  407. struct_lines.append(
  408. f"pub {field_name}: *const {as_rust_struct_type(util.extract_ptr_type(field_type), prefix)}"
  409. )
  410. default_lines.append(
  411. f"{field_name}: core::ptr::null()"
  412. )
  413. elif is_struct_ptr(field_type):
  414. struct_lines.append(
  415. f"pub {field_name}: *mut {as_rust_struct_type(util.extract_ptr_type(field_type), prefix)}"
  416. )
  417. default_lines.append(
  418. f"{field_name}: core::ptr::null_mut()"
  419. )
  420. elif util.is_func_ptr(field_type):
  421. struct_lines.append(
  422. f"pub {field_name}: Option<extern \"C\" fn({funcptr_args_c(field_type, prefix)}){funcptr_result_c(field_type)}>"
  423. )
  424. default_lines.append(
  425. f"{field_name}: None"
  426. )
  427. elif util.is_1d_array_type(field_type):
  428. array_type = util.extract_array_type(field_type)
  429. array_sizes = util.extract_array_sizes(field_type)
  430. if is_prim_type(array_type) or is_struct_type(array_type):
  431. if is_prim_type(array_type):
  432. rust_type = as_rust_prim_type(array_type)
  433. def_val = type_default_value(array_type)
  434. elif is_struct_type(array_type) or is_enum_type(array_type):
  435. rust_type = as_rust_struct_type(array_type, prefix)
  436. def_val = f"{rust_type}::new()"
  437. else:
  438. sys.exit(f"ERROR gen_struct is_1d_array_type: {array_type}")
  439. t0 = f"[{rust_type}; {array_sizes[0]}]"
  440. # t1 = f"&{rust_type}"
  441. struct_lines.append(
  442. f"pub {field_name}: {t0}"
  443. )
  444. default_lines.append(
  445. f"{field_name}: [{def_val}; {array_sizes[0]}]"
  446. )
  447. elif util.is_const_void_ptr(array_type):
  448. struct_lines.append(
  449. f"pub {field_name}: [*const core::ffi::c_void; {array_sizes[0]}]"
  450. )
  451. default_lines.append(
  452. f"{field_name}: [core::ptr::null(); {array_sizes[0]}]"
  453. )
  454. else:
  455. sys.exit(
  456. f"ERROR gen_struct: array {field_name}: {field_type} => [{array_type}: {array_sizes[0]}]"
  457. )
  458. elif util.is_2d_array_type(field_type):
  459. array_type = util.extract_array_type(field_type)
  460. array_sizes = util.extract_array_sizes(field_type)
  461. if is_prim_type(array_type):
  462. rust_type = as_rust_prim_type(array_type)
  463. def_val = type_default_value(array_type)
  464. elif is_struct_type(array_type):
  465. rust_type = as_rust_struct_type(array_type, prefix)
  466. def_val = f"{rust_type}::new()"
  467. else:
  468. sys.exit(f"ERROR gen_struct is_2d_array_type: {array_type}")
  469. struct_lines.append(
  470. f"pub {field_name}: [[{rust_type}; {array_sizes[1]}]; {array_sizes[0]}]"
  471. )
  472. default_lines.append(
  473. f"{field_name}: [[{def_val}; {array_sizes[1]}]; {array_sizes[0]}]"
  474. )
  475. else:
  476. sys.exit(f"ERROR gen_struct: {field_name}: {field_type};")
  477. #
  478. # TODO: Is this the best way to have zero-initialization with support for constants?
  479. # core::mem::zeroed() cleaner?
  480. #
  481. l("#[repr(C)]")
  482. l("#[derive(Copy, Clone, Debug)]")
  483. l(f"pub struct {rust_struct_type} {{")
  484. for line in struct_lines:
  485. l(f" {line},")
  486. l("}")
  487. l(f"impl {rust_struct_type} {{")
  488. l(" pub const fn new() -> Self {")
  489. l(" Self {")
  490. for line in default_lines:
  491. l(f" {line},")
  492. l(" }")
  493. l(" }")
  494. l("}")
  495. l(f"impl Default for {rust_struct_type} {{")
  496. l(" fn default() -> Self {")
  497. l(" Self::new()")
  498. l(" }")
  499. l("}")
  500. def gen_consts(decl, prefix):
  501. for item in decl["items"]:
  502. #
  503. # TODO: What type should these constants have? Currently giving all `usize`
  504. # unless specifically overriden by `special_constant_types`
  505. #
  506. item_name = check_override(item["name"])
  507. if item_name in special_constant_types:
  508. special_type = special_constant_types[item_name]
  509. l(f"pub const {as_upper_snake_case(item_name, prefix)}: {special_type} = {item['value']};")
  510. else:
  511. l(f"pub const {as_upper_snake_case(item_name, prefix)}: usize = {item['value']};")
  512. def gen_enum(decl, prefix):
  513. enum_name = check_override(decl["name"])
  514. names = [
  515. as_enum_item_name(check_override(f"{decl['name']}::{item['name']}", item['name'])) for item in decl["items"]
  516. ]
  517. is_u32 = False
  518. for name in names:
  519. if name == "ForceU32":
  520. is_u32 = True
  521. break
  522. l("#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]")
  523. if is_u32:
  524. l("#[repr(u32)]")
  525. else:
  526. l("#[repr(i32)]")
  527. rust_enum_name = as_rust_enum_type(enum_name, prefix)
  528. l(f"pub enum {rust_enum_name} {{")
  529. for item_name, item in zip(names, decl["items"]):
  530. if item_name != "ForceU32":
  531. if "value" in item:
  532. l(f" {item_name} = {item['value']},")
  533. else:
  534. l(f" {item_name},")
  535. l("}")
  536. default_item = enum_default_item(enum_name)
  537. l(f"impl {rust_enum_name} {{")
  538. l(" pub const fn new() -> Self {")
  539. l(f" Self::{default_item}")
  540. l(" }")
  541. l("}")
  542. l(f"impl Default for {rust_enum_name} {{")
  543. l(" fn default() -> Self {")
  544. l(f" Self::{default_item}")
  545. l(" }")
  546. l("}")
  547. def gen_func_c(decl, prefix):
  548. l("pub extern \"C\" {")
  549. l(f" fn {decl['name']}({funcdecl_args_c(decl, prefix)}){funcdecl_result_c(decl, prefix)};")
  550. l("}")
  551. def gen_c_funcs(funcs):
  552. l("pub mod ffi {")
  553. l(" #![allow(unused_imports)]")
  554. l(" use super::*;")
  555. l(" extern \"C\" {")
  556. for decl, prefix in funcs:
  557. l(f" pub fn {decl['name']}({funcdecl_args_c(decl, prefix)}){funcdecl_result_c(decl, prefix)};")
  558. l(" }")
  559. l("}")
  560. def gen_rust_funcs(funcs):
  561. for decl, prefix in funcs:
  562. gen_func_rust(decl, prefix)
  563. def gen_func_rust(decl, prefix):
  564. c_func_name = decl["name"]
  565. rust_func_name = util.as_lower_snake_case(check_override(decl["name"]), prefix)
  566. rust_res_type = funcdecl_result_rust(decl, prefix)
  567. if c_func_name in c_callbacks:
  568. c_res_type = funcdecl_result_c(decl, prefix)
  569. l("#[inline]")
  570. l(f'pub extern "C" fn {c_func_name}({funcdecl_args_c(decl, prefix)}){c_res_type} {{')
  571. l(" unsafe {")
  572. s = f" ffi::{c_func_name}("
  573. for i, param_decl in enumerate(decl["params"]):
  574. if i > 0:
  575. s += ", "
  576. arg_name = param_decl["name"]
  577. s += arg_name
  578. s += ")"
  579. l(s)
  580. l(" }")
  581. l("}")
  582. else:
  583. l("#[inline]")
  584. l(f"pub fn {rust_func_name}({funcdecl_args_rust(decl, prefix)}){rust_res_type} {{")
  585. for i, param_decl in enumerate(decl["params"]):
  586. arg_name = param_decl["name"]
  587. arg_type = param_decl["type"]
  588. if util.is_string_ptr(arg_type):
  589. l(f" let tmp_{i} = std::ffi::CString::new({arg_name}).unwrap();")
  590. l(" unsafe {")
  591. if is_rust_string(rust_res_type):
  592. # special case: convert C string to rust string slice
  593. s = f" c_char_ptr_to_rust_str(ffi::{c_func_name}("
  594. else:
  595. s = f" ffi::{c_func_name}("
  596. for i, param_decl in enumerate(decl["params"]):
  597. if i > 0:
  598. s += ", "
  599. arg_name = param_decl["name"]
  600. arg_type = param_decl["type"]
  601. if util.is_string_ptr(arg_type):
  602. s += f"tmp_{i}.as_ptr()"
  603. else:
  604. s += arg_name
  605. if is_rust_string(rust_res_type):
  606. s += ")"
  607. s += ")"
  608. l(s)
  609. l(" }")
  610. l("}")
  611. def pre_parse(inp):
  612. global struct_types
  613. global enum_types
  614. for decl in inp["decls"]:
  615. kind = decl["kind"]
  616. if kind == "struct":
  617. struct_types.append(decl["name"])
  618. elif kind == "enum":
  619. enum_name = decl["name"]
  620. enum_types.append(enum_name)
  621. enum_items[enum_name] = []
  622. for item in decl["items"]:
  623. enum_items[enum_name].append(as_enum_item_name(item["name"]))
  624. def gen_imports(inp, dep_prefixes):
  625. for dep_prefix in dep_prefixes:
  626. dep_module_name = module_names[dep_prefix]
  627. # l(f'const {dep_prefix[:-1]} = @import("{dep_module_name}.rs");')
  628. l(f'use crate::{dep_module_name} as {dep_prefix[:-1]};')
  629. l("")
  630. def gen_helpers(inp):
  631. l("/// Helper function to convert a C string to a rust string slice")
  632. l("#[inline]")
  633. l("fn c_char_ptr_to_rust_str(c_char_ptr: *const core::ffi::c_char) -> &'static str {")
  634. l(" let c_str = unsafe { core::ffi::CStr::from_ptr(c_char_ptr) };")
  635. l(" c_str.to_str().expect(\"c_char_ptr contained invalid Utf8 Data\")")
  636. l("}")
  637. l("")
  638. if inp['prefix'] in ['sg_', 'sdtx_', 'sshape_', 'sapp_']:
  639. l("/// Helper function to cast a rust slice into a sokol Range")
  640. l(f"pub fn slice_as_range<T>(data: &[T]) -> {range_struct_name} {{")
  641. l(f" {range_struct_name} {{ size: data.len() * std::mem::size_of::<T>(), ptr: data.as_ptr() as *const _ }}")
  642. l("}")
  643. l("/// Helper function to cast a rust reference into a sokol Range")
  644. l(f"pub fn value_as_range<T>(value: &T) -> {range_struct_name} {{")
  645. l(f" {range_struct_name} {{ size: std::mem::size_of::<T>(), ptr: value as *const T as *const _ }}")
  646. l("}")
  647. l("")
  648. l(f"impl<T> From<&[T]> for {range_struct_name} {{")
  649. l(" #[inline]")
  650. l(" fn from(data: &[T]) -> Self {")
  651. l(" slice_as_range(data)")
  652. l(" }")
  653. l("}")
  654. l(f"impl<T> From<&T> for {range_struct_name} {{")
  655. l(" #[inline]")
  656. l(" fn from(value: &T) -> Self {")
  657. l(" value_as_range(value)")
  658. l(" }")
  659. l("}")
  660. l("")
  661. # if inp["prefix"] == "sdtx_":
  662. # l("/// std.fmt compatible Writer")
  663. # l("pub const Writer = struct {")
  664. # l(" pub const Error = error { };")
  665. # l(" pub fn writeAll(self: Writer, bytes: []const u8) Error!void {")
  666. # l(" _ = self;")
  667. # l(" for (bytes) |byte| {")
  668. # l(" putc(byte);")
  669. # l(" }")
  670. # l(" }")
  671. # l(" pub fn writeByteNTimes(self: Writer, byte: u8, n: u64) Error!void {")
  672. # l(" _ = self;")
  673. # l(" var i: u64 = 0;")
  674. # l(" while (i < n): (i += 1) {")
  675. # l(" putc(byte);")
  676. # l(" }")
  677. # l(" }")
  678. # l("};")
  679. # l("// std.fmt-style formatted print")
  680. # l("pub fn print(comptime fmt: anytype, args: anytype) void {")
  681. # l(" var writer: Writer = .{};")
  682. # l(' @import("std").fmt.format(writer, fmt, args) catch {};')
  683. # l("}")
  684. # l("")
  685. def gen_module(inp, dep_prefixes):
  686. module = inp['module']
  687. if module in module_requires_rust_feature:
  688. feature = module_requires_rust_feature[module]
  689. l(f"//! To use this module, enable the feature \"{feature}\"")
  690. l("// machine generated, do not edit")
  691. l("")
  692. l("#![allow(dead_code)]")
  693. l("#![allow(unused_imports)]")
  694. l("")
  695. gen_imports(inp, dep_prefixes)
  696. gen_helpers(inp)
  697. pre_parse(inp)
  698. prefix = inp["prefix"]
  699. funcs = []
  700. for decl in inp["decls"]:
  701. #
  702. # HACK: gen_ir.py accidentally marks all sg_imgui_ declarations as is_dep since sg_imgui
  703. # depends on sg_a but also starts with sg_... Fix gen_ir.py to remove this hack
  704. #
  705. dep_hack = False
  706. if module == "gfx_imgui":
  707. dep_hack = "name" in decl and decl["name"].startswith("sg_imgui_")
  708. if not decl["is_dep"] or dep_hack:
  709. kind = decl["kind"]
  710. if kind == "consts":
  711. gen_consts(decl, prefix)
  712. elif not check_ignore(decl["name"]):
  713. if kind == "struct":
  714. gen_struct(decl, prefix)
  715. elif kind == "enum":
  716. gen_enum(decl, prefix)
  717. elif kind == "func":
  718. funcs.append((decl, prefix))
  719. gen_c_funcs(funcs)
  720. gen_rust_funcs(funcs)
  721. def prepare():
  722. print("=== Generating Rust bindings:")
  723. if not os.path.isdir("sokol-rust/src/sokol"):
  724. os.makedirs("sokol-rust/src/sokol")
  725. if not os.path.isdir("sokol-rust/src/sokol/c"):
  726. os.makedirs("sokol-rust/src/sokol/c")
  727. with open("sokol-rust/src/lib.rs", "w", newline="\n") as f_outp:
  728. f_outp.write("//! Automatically generated sokol bindings for Rust\n\n")
  729. def gen(c_header_path, c_prefix, dep_c_prefixes):
  730. if c_prefix not in module_names:
  731. print(f' >> warning: skipping generation for {c_prefix} prefix...')
  732. return
  733. module_name = module_names[c_prefix]
  734. c_source_path = c_source_paths[c_prefix]
  735. print(f' {c_header_path} => {module_name}')
  736. reset_globals()
  737. c_path_in_project = f'sokol-rust/src/sokol/c/{os.path.basename(c_header_path)}'
  738. shutil.copyfile(c_header_path, c_path_in_project)
  739. ir = gen_ir.gen(c_header_path, c_source_path, module_name, c_prefix, dep_c_prefixes)
  740. gen_module(ir, dep_c_prefixes)
  741. output_path = f"sokol-rust/src/{ir['module']}.rs"
  742. with open(output_path, 'w', newline='\n') as f_outp:
  743. f_outp.write(out_lines)
  744. with open("sokol-rust/src/lib.rs", "a", newline="\n") as f_outp:
  745. module = ir['module']
  746. if module in module_requires_rust_feature:
  747. feature = module_requires_rust_feature[module]
  748. f_outp.write(f"/// Enable feature \"{feature}\" to use\n")
  749. f_outp.write(f"#[cfg(feature=\"{feature}\")]\n")
  750. f_outp.write(f"pub mod {module};\n")