gen_d.py 17 KB

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