2
0

gen_rust.py 28 KB

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