gen_jai.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #-------------------------------------------------------------------------------
  2. # gen_jai.py
  3. #
  4. # Generate Jai bindings.
  5. #-------------------------------------------------------------------------------
  6. import gen_ir
  7. import gen_util as util
  8. import os, shutil, sys
  9. bindings_root = 'sokol-jai'
  10. c_root = f'{bindings_root}/sokol/c'
  11. module_root = f'{bindings_root}/sokol'
  12. module_names = {
  13. 'slog_': 'log',
  14. 'sg_': 'gfx',
  15. 'sapp_': 'app',
  16. 'stm_': 'time',
  17. 'saudio_': 'audio',
  18. 'sgl_': 'gl',
  19. 'sdtx_': 'debugtext',
  20. 'sshape_': 'shape',
  21. 'sglue_': 'glue',
  22. }
  23. system_libs = {
  24. 'sg_': {
  25. 'windows': {
  26. 'd3d11': '#system_library,link_always "gdi32"; #system_library,link_always "dxguid"; #system_library,link_always "user32"; #system_library,link_always "shell32"; #system_library,link_always "d3d11";',
  27. 'gl': '#system_library,link_always "gdi32"; #system_library,link_always "dxguid"; #system_library,link_always "user32"; #system_library,link_always "shell32";',
  28. },
  29. 'macos': {
  30. 'metal': '#library,link_always "../../libclang_rt.osx"; #system_library,link_always "Cocoa"; #system_library,link_always "QuartzCore"; #system_library,link_always "Metal"; #system_library,link_always "MetalKit";',
  31. 'gl': '#system_library,link_always "Cocoa"; #system_library,link_always "QuartzCore"; #system_library,link_always "OpenGL";',
  32. },
  33. 'linux': {
  34. 'gl': '#system_library,link_always "libXcursor"; #system_library,link_always "libX11"; #system_library,link_always "libXi"; #system_library,link_always "libGL";',
  35. }
  36. },
  37. 'sapp_': {
  38. 'windows': {
  39. 'd3d11': '#system_library,link_always "gdi32"; #system_library,link_always "dxguid"; #system_library,link_always "user32"; #system_library,link_always "shell32";',
  40. 'gl': '#system_library,link_always "gdi32"; #system_library,link_always "dxguid"; #system_library,link_always "user32"; #system_library,link_always "shell32";',
  41. },
  42. 'macos': {
  43. 'metal': '#library "../../libclang_rt.osx"; #system_library,link_always "Cocoa"; #system_library,link_always "QuartzCore";',
  44. 'gl': '#system_library,link_always "Cocoa"; #system_library,link_always "QuartzCore";',
  45. },
  46. 'linux': {
  47. 'gl': '#system_library,link_always "libXcursor"; #system_library,link_always "libX11"; #system_library,link_always "libXi"; #system_library,link_always "libGL";',
  48. }
  49. },
  50. 'saudio_': {
  51. 'windows': {
  52. 'd3d11': '#system_library,link_always "ole32";',
  53. 'gl': '#system_library,link_always "ole32";',
  54. },
  55. 'macos': {
  56. 'metal': '#system_library,link_always "AudioToolbox";',
  57. 'gl': '#system_library,link_always "AudioToolbox";',
  58. },
  59. 'linux': {
  60. 'gl': '#system_library,link_always "asound"; #system_library,link_always "dl"; #system_library,link_always "pthread";',
  61. }
  62. }
  63. }
  64. c_source_names = {
  65. 'slog_': 'sokol_log.c',
  66. 'sg_': 'sokol_gfx.c',
  67. 'sapp_': 'sokol_app.c',
  68. 'sapp_sg': 'sokol_glue.c',
  69. 'stm_': 'sokol_time.c',
  70. 'saudio_': 'sokol_audio.c',
  71. 'sgl_': 'sokol_gl.c',
  72. 'sdtx_': 'sokol_debugtext.c',
  73. 'sshape_': 'sokol_shape.c',
  74. 'sglue_': 'sokol_glue.c',
  75. }
  76. ignores = [
  77. 'sdtx_printf',
  78. 'sdtx_vprintf',
  79. ]
  80. # NOTE: syntax for function results: "func_name.RESULT"
  81. overrides = {
  82. 'context': 'ctx', # reserved keyword
  83. 'SGL_NO_ERROR': 'SGL_ERROR_NO_ERROR',
  84. }
  85. prim_types = {
  86. 'int': 's32',
  87. 'bool': 'bool',
  88. 'char': 'u8',
  89. 'int8_t': 's8',
  90. 'uint8_t': 'u8',
  91. 'int16_t': 's16',
  92. 'uint16_t': 'u16',
  93. 'int32_t': 's32',
  94. 'uint32_t': 'u32',
  95. 'int64_t': 's64',
  96. 'uint64_t': 'u64',
  97. 'float': 'float',
  98. 'double': 'float64',
  99. 'uintptr_t': 'u64',
  100. 'intptr_t': 's64',
  101. 'size_t': 'u64'
  102. }
  103. prim_defaults = {
  104. 'int': '0',
  105. 'bool': 'false',
  106. 'int8_t': '0',
  107. 'uint8_t': '0',
  108. 'int16_t': '0',
  109. 'uint16_t': '0',
  110. 'int32_t': '0',
  111. 'uint32_t': '0',
  112. 'int64_t': '0',
  113. 'uint64_t': '0',
  114. 'float': '0.0',
  115. 'double': '0.0',
  116. 'uintptr_t': '0',
  117. 'intptr_t': '0',
  118. 'size_t': '0'
  119. }
  120. struct_types = []
  121. enum_types = []
  122. enum_items = {}
  123. out_lines = ''
  124. def reset_globals():
  125. global struct_types
  126. global enum_types
  127. global enum_items
  128. global out_lines
  129. struct_types = []
  130. enum_types = []
  131. enum_items = {}
  132. out_lines = ''
  133. def l(s):
  134. global out_lines
  135. out_lines += s + '\n'
  136. def check_override(name, default=None):
  137. if name in overrides:
  138. return overrides[name]
  139. elif default is None:
  140. return name
  141. else:
  142. return default
  143. def check_ignore(name):
  144. return name in ignores
  145. # PREFIX_BLA_BLUB to BLA_BLUB, prefix_bla_blub to bla_blub
  146. def as_snake_case(s, prefix):
  147. outp = s
  148. if outp.lower().startswith(prefix):
  149. outp = outp[len(prefix):]
  150. return outp
  151. def get_jai_module_path(c_prefix):
  152. return f'{module_root}/{module_names[c_prefix]}'
  153. def get_csource_path(c_prefix):
  154. return f'{c_root}/{c_source_names[c_prefix]}'
  155. def make_jai_module_directory(c_prefix):
  156. path = get_jai_module_path(c_prefix)
  157. if not os.path.isdir(path):
  158. os.makedirs(path)
  159. def as_prim_type(s):
  160. return prim_types[s]
  161. def as_struct_or_enum_type(s, prefix):
  162. return s
  163. # PREFIX_ENUM_BLA_BLUB => BLA_BLUB, _PREFIX_ENUM_BLA_BLUB => BLA_BLUB
  164. def as_enum_item_name(s):
  165. outp = s.lstrip('_')
  166. parts = outp.split('_')[2:]
  167. outp = '_'.join(parts)
  168. if outp[0].isdigit():
  169. outp = '_' + outp
  170. return outp
  171. def enum_default_item(enum_name):
  172. return enum_items[enum_name][0]
  173. def is_prim_type(s):
  174. return s in prim_types
  175. def is_int_type(s):
  176. return s == "int"
  177. def is_struct_type(s):
  178. return s in struct_types
  179. def is_enum_type(s):
  180. return s in enum_types
  181. def is_const_prim_ptr(s):
  182. for prim_type in prim_types:
  183. if s == f"const {prim_type} *":
  184. return True
  185. return False
  186. def is_prim_ptr(s):
  187. for prim_type in prim_types:
  188. if s == f"{prim_type} *":
  189. return True
  190. return False
  191. def is_const_struct_ptr(s):
  192. for struct_type in struct_types:
  193. if s == f"const {struct_type} *":
  194. return True
  195. return False
  196. def type_default_value(s):
  197. return prim_defaults[s]
  198. def map_type(type, prefix, sub_type):
  199. if sub_type not in ['c_arg', 'struct_field']:
  200. sys.exit(f"Error: map_type(): unknown sub_type '{sub_type}")
  201. if type == "void":
  202. return ""
  203. elif is_struct_type(type):
  204. return as_struct_or_enum_type(type, prefix)
  205. elif is_enum_type(type):
  206. return as_struct_or_enum_type(type, prefix)
  207. elif util.is_void_ptr(type):
  208. return "*void"
  209. elif util.is_const_void_ptr(type):
  210. return "*void"
  211. elif util.is_string_ptr(type):
  212. return "*u8"
  213. elif is_const_struct_ptr(type):
  214. return f"*{as_struct_or_enum_type(util.extract_ptr_type(type), prefix)}"
  215. elif is_prim_ptr(type):
  216. return f"*{as_prim_type(util.extract_ptr_type(type))}"
  217. elif is_const_prim_ptr(type):
  218. return f"*{as_prim_type(util.extract_ptr_type(type))}"
  219. elif util.is_1d_array_type(type):
  220. array_type = util.extract_array_type(type)
  221. array_sizes = util.extract_array_sizes(type)
  222. return f"[{array_sizes[0]}]{map_type(array_type, prefix, sub_type)}"
  223. elif util.is_2d_array_type(type):
  224. array_type = util.extract_array_type(type)
  225. array_sizes = util.extract_array_sizes(type)
  226. return f"[{array_sizes[0]}][{array_sizes[1]}]{map_type(array_type, prefix, sub_type)}"
  227. elif util.is_func_ptr(type):
  228. res_type = funcptr_result_c(type, prefix)
  229. res_str = '' if res_type == '' else f' -> {res_type}'
  230. return f'({funcptr_args_c(type, prefix)}){res_str} #c_call'
  231. elif is_prim_type(type):
  232. return as_prim_type(type)
  233. else:
  234. sys.exit(f"Error map_type(): unknown type '{type}'")
  235. def funcdecl_args_c(decl, prefix):
  236. s = ''
  237. func_name = decl['name']
  238. for param_decl in decl['params']:
  239. if s != '':
  240. s += ', '
  241. param_name = param_decl['name']
  242. param_type = check_override(f'{func_name}.{param_name}', default=param_decl['type'])
  243. s += f"{param_name}: {map_type(param_type, prefix, 'c_arg')}"
  244. return s
  245. def funcptr_args_c(field_type, prefix):
  246. tokens = field_type[field_type.index('(*)')+4:-1].split(',')
  247. s = ''
  248. arg_index = 0
  249. for token in tokens:
  250. arg_type = token.strip()
  251. if s != '':
  252. s += ', '
  253. c_arg = map_type(arg_type, prefix, 'c_arg')
  254. if c_arg == '':
  255. return ''
  256. else:
  257. s += f'a{arg_index}: {c_arg}'
  258. arg_index += 1
  259. return s
  260. def funcptr_result_c(field_type, prefix):
  261. res_type = field_type[:field_type.index('(*)')].strip()
  262. return map_type(res_type, prefix, 'c_arg')
  263. def funcdecl_result_c(decl, prefix):
  264. func_name = decl['name']
  265. decl_type = decl['type']
  266. res_c_type = decl_type[:decl_type.index('(')].strip()
  267. return map_type(check_override(f'{func_name}.RESULT', default=res_c_type), prefix, 'c_arg')
  268. def get_system_libs(module, platform, backend):
  269. if module in system_libs:
  270. if platform in system_libs[module]:
  271. if backend in system_libs[module][platform]:
  272. libs = system_libs[module][platform][backend]
  273. if libs != '':
  274. return f"{libs}"
  275. return ''
  276. def gen_c_imports(inp, c_prefix, prefix):
  277. module_name = inp["module"]
  278. clib_prefix = f'sokol_{module_name}'
  279. clib_import = f'{clib_prefix}_clib'
  280. windows_d3d11_libs = get_system_libs(prefix, 'windows', 'd3d11')
  281. windows_gl_libs = get_system_libs(prefix, 'windows', 'gl')
  282. macos_metal_libs = get_system_libs(prefix, 'macos', 'metal')
  283. macos_gl_libs = get_system_libs(prefix, 'macos', 'gl')
  284. linux_gl_libs = get_system_libs(prefix, 'linux', 'gl')
  285. l( '#module_parameters(DEBUG := false, USE_GL := false, USE_DLL := false);')
  286. l( '')
  287. l( '#scope_export;')
  288. l( '')
  289. l( '#if OS == .WINDOWS {')
  290. l( ' #if USE_DLL {')
  291. l( ' #if USE_GL {')
  292. l(f' {windows_gl_libs}')
  293. l(f' #if DEBUG {{ {clib_import} :: #library "{clib_prefix}_windows_x64_gl_debug"; }}')
  294. l(f' else {{ {clib_import} :: #library "{clib_prefix}_windows_x64_gl_release"; }}')
  295. l( ' } else {')
  296. l(f' {windows_d3d11_libs}')
  297. l(f' #if DEBUG {{ {clib_import} :: #library "{clib_prefix}_windows_x64_d3d11_debug"; }}')
  298. l(f' else {{ {clib_import} :: #library "{clib_prefix}_windows_x64_d3d11_release"; }}')
  299. l( ' }')
  300. l( ' } else {')
  301. l( ' #if USE_GL {')
  302. l(f' {windows_gl_libs}')
  303. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_windows_x64_gl_debug"; }}')
  304. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_windows_x64_gl_release"; }}')
  305. l( ' } else {')
  306. l(f' {windows_d3d11_libs}')
  307. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_windows_x64_d3d11_debug"; }}')
  308. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_windows_x64_d3d11_release"; }}')
  309. l( ' }')
  310. l( ' }')
  311. l( '}')
  312. l( 'else #if OS == .MACOS {')
  313. l( ' #if USE_DLL {')
  314. l(f' #if USE_GL && CPU == .ARM64 && DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_arm64_gl_debug.dylib"; }}')
  315. l(f' else #if USE_GL && CPU == .ARM64 && !DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_arm64_gl_release.dylib"; }}')
  316. l(f' else #if USE_GL && CPU == .X64 && DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_x64_gl_debug.dylib"; }}')
  317. l(f' else #if USE_GL && CPU == .X64 && !DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_x64_gl_release.dylib"; }}')
  318. l(f' else #if !USE_GL && CPU == .ARM64 && DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_arm64_metal_debug.dylib"; }}')
  319. l(f' else #if !USE_GL && CPU == .ARM64 && !DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_arm64_metal_release.dylib"; }}')
  320. l(f' else #if !USE_GL && CPU == .X64 && DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_x64_metal_debug.dylib"; }}')
  321. l(f' else #if !USE_GL && CPU == .X64 && !DEBUG {{ {clib_import} :: #library "../dylib/sokol_dylib_macos_x64_metal_release.dylib"; }}')
  322. l( ' } else {')
  323. l( ' #if USE_GL {')
  324. l(f' {macos_gl_libs}')
  325. l( ' #if CPU == .ARM64 {')
  326. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_arm64_gl_debug"; }}')
  327. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_arm64_gl_release"; }}')
  328. l( ' } else {')
  329. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_x64_gl_debug"; }}')
  330. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_x64_gl_release"; }}')
  331. l( ' }')
  332. l( ' } else {')
  333. l(f' {macos_metal_libs}')
  334. l( ' #if CPU == .ARM64 {')
  335. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_arm64_metal_debug"; }}')
  336. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_arm64_metal_release"; }}')
  337. l( ' } else {')
  338. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_x64_metal_debug"; }}')
  339. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_macos_x64_metal_release"; }}')
  340. l( ' }')
  341. l( ' }')
  342. l( ' }')
  343. l( '} else #if OS == .LINUX {')
  344. if linux_gl_libs:
  345. l(f' {linux_gl_libs}')
  346. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_linux_x64_gl_debug"; }}')
  347. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_linux_x64_gl_release"; }}')
  348. l( '} else #if OS == .WASM {')
  349. l(f' #if DEBUG {{ {clib_import} :: #library,no_dll "{clib_prefix}_wasm_gl_debug"; }}')
  350. l(f' else {{ {clib_import} :: #library,no_dll "{clib_prefix}_wasm_gl_release"; }}')
  351. l( '} else {')
  352. l( ' log_error("This OS is currently not supported");')
  353. l( '}')
  354. l( '')
  355. prefix = inp['prefix']
  356. for decl in inp['decls']:
  357. if decl['kind'] == 'func' and not decl['is_dep'] and not check_ignore(decl['name']):
  358. args = funcdecl_args_c(decl, prefix)
  359. res_type = funcdecl_result_c(decl, prefix)
  360. res_str = '-> void' if res_type == '' else f'-> {res_type}'
  361. l(f"{decl['name']} :: ({args}) {res_str} #foreign {clib_import};")
  362. l('')
  363. def gen_consts(decl, prefix):
  364. for item in decl['items']:
  365. item_name = check_override(item['name'])
  366. l(f"{as_snake_case(item_name, prefix)} :: {item['value']};")
  367. l('')
  368. def gen_struct(decl, prefix):
  369. c_struct_name = check_override(decl['name'])
  370. struct_name = as_struct_or_enum_type(c_struct_name, prefix)
  371. l(f'{struct_name} :: struct {{')
  372. for field in decl['fields']:
  373. field_name = check_override(field['name'])
  374. field_type = map_type(check_override(f'{c_struct_name}.{field_name}', default=field['type']), prefix, 'struct_field')
  375. # any field name starting with _ is considered private
  376. if field_name.startswith('_'):
  377. l(f' _ : {field_type};')
  378. else:
  379. l(f' {field_name} : {field_type};')
  380. l('}')
  381. l('')
  382. def gen_enum(decl, prefix):
  383. enum_name = check_override(decl['name'])
  384. l(f'{as_struct_or_enum_type(enum_name, prefix)} :: enum u32 {{')
  385. for item in decl['items']:
  386. item_name = as_enum_item_name(check_override(item['name']))
  387. if item_name != 'FORCE_U32' and item_name != 'NUM':
  388. if 'value' in item:
  389. l(f" {item_name} :: {item['value']};")
  390. else:
  391. l(f" {item_name};")
  392. l('}')
  393. l('')
  394. def gen_imports(dep_prefixes):
  395. for dep_prefix in dep_prefixes:
  396. dep_module_name = module_names[dep_prefix]
  397. l(f'#import,dir "../{dep_module_name}"(DEBUG = USE_DLL, USE_GL = USE_DLL, USE_DLL = USE_DLL);')
  398. l('')
  399. def gen_helpers(inp):
  400. if inp['prefix'] == 'sdtx_':
  401. l('sdtx_printf :: (s: string, args: ..Any) {')
  402. l(' #import "Basic";')
  403. l(' fstr := tprint(s, ..args);')
  404. l(' sdtx_putr(to_c_string(fstr), xx fstr.count);')
  405. l('}')
  406. def gen_module(inp, c_prefix, dep_prefixes):
  407. pre_parse(inp)
  408. l('// machine generated, do not edit')
  409. gen_imports(dep_prefixes)
  410. gen_helpers(inp)
  411. prefix = inp['prefix']
  412. gen_c_imports(inp, c_prefix, prefix)
  413. for decl in inp['decls']:
  414. if not decl['is_dep']:
  415. kind = decl['kind']
  416. if kind == 'consts':
  417. gen_consts(decl, prefix)
  418. elif not check_ignore(decl['name']):
  419. if kind == 'struct':
  420. gen_struct(decl, prefix)
  421. elif kind == 'enum':
  422. gen_enum(decl, prefix)
  423. def pre_parse(inp):
  424. global struct_types
  425. global enum_types
  426. for decl in inp['decls']:
  427. kind = decl['kind']
  428. if kind == 'struct':
  429. struct_types.append(decl['name'])
  430. elif kind == 'enum':
  431. enum_name = decl['name']
  432. enum_types.append(enum_name)
  433. enum_items[enum_name] = []
  434. for item in decl['items']:
  435. enum_items[enum_name].append(as_enum_item_name(item['name']))
  436. def prepare():
  437. print('=== Generating Jai bindings:')
  438. if not os.path.isdir(module_root):
  439. os.makedirs(module_root)
  440. if not os.path.isdir(c_root):
  441. os.makedirs(c_root)
  442. def gen(c_header_path, c_prefix, dep_c_prefixes):
  443. if not c_prefix in module_names:
  444. print(f' >> warning: skipping generation for {c_prefix} prefix...')
  445. return
  446. reset_globals()
  447. make_jai_module_directory(c_prefix)
  448. print(f' {c_header_path} => {module_names[c_prefix]}')
  449. shutil.copyfile(c_header_path, f'{c_root}/{os.path.basename(c_header_path)}')
  450. csource_path = get_csource_path(c_prefix)
  451. module_name = module_names[c_prefix]
  452. ir = gen_ir.gen(c_header_path, csource_path, module_name, c_prefix, dep_c_prefixes)
  453. gen_module(ir, c_prefix, dep_c_prefixes)
  454. with open(f"{module_root}/{ir['module']}/module.jai", 'w', newline='\n') as f_outp:
  455. f_outp.write(out_lines)