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