gendynapi.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #!/usr/bin/env python3
  2. # Simple DirectMedia Layer
  3. # Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
  4. #
  5. # This software is provided 'as-is', without any express or implied
  6. # warranty. In no event will the authors be held liable for any damages
  7. # arising from the use of this software.
  8. #
  9. # Permission is granted to anyone to use this software for any purpose,
  10. # including commercial applications, and to alter it and redistribute it
  11. # freely, subject to the following restrictions:
  12. #
  13. # 1. The origin of this software must not be misrepresented; you must not
  14. # claim that you wrote the original software. If you use this software
  15. # in a product, an acknowledgment in the product documentation would be
  16. # appreciated but is not required.
  17. # 2. Altered source versions must be plainly marked as such, and must not be
  18. # misrepresented as being the original software.
  19. # 3. This notice may not be removed or altered from any source distribution.
  20. # WHAT IS THIS?
  21. # When you add a public API to SDL, please run this script, make sure the
  22. # output looks sane (git diff, it adds to existing files), and commit it.
  23. # It keeps the dynamic API jump table operating correctly.
  24. #
  25. # OS-specific API:
  26. # After running the script, you have to manually add #ifdef __WIN32__
  27. # or similar around the function in 'SDL_dynapi_procs.h'
  28. #
  29. import argparse
  30. import json
  31. import os
  32. import pathlib
  33. import pprint
  34. import re
  35. SDL_ROOT = pathlib.Path(__file__).resolve().parents[2]
  36. SDL_INCLUDE_DIR = SDL_ROOT / "include/SDL3"
  37. SDL_DYNAPI_PROCS_H = SDL_ROOT / "src/dynapi/SDL_dynapi_procs.h"
  38. SDL_DYNAPI_OVERRIDES_H = SDL_ROOT / "src/dynapi/SDL_dynapi_overrides.h"
  39. SDL_DYNAPI_SYM = SDL_ROOT / "src/dynapi/SDL_dynapi.sym"
  40. full_API = []
  41. def main():
  42. # Parse 'sdl_dynapi_procs_h' file to find existing functions
  43. existing_procs = find_existing_procs()
  44. # Get list of SDL headers
  45. sdl_list_includes = get_header_list()
  46. reg_externC = re.compile('.*extern[ "]*C[ "].*')
  47. reg_comment_remove_content = re.compile('\/\*.*\*/')
  48. reg_parsing_function = re.compile('(.*SDLCALL[^\(\)]*) ([a-zA-Z0-9_]+) *\((.*)\) *;.*')
  49. #eg:
  50. # void (SDLCALL *callback)(void*, int)
  51. # \1(\2)\3
  52. reg_parsing_callback = re.compile('([^\(\)]*)\(([^\(\)]+)\)(.*)')
  53. for filename in sdl_list_includes:
  54. if args.debug:
  55. print("Parse header: %s" % filename)
  56. input = open(filename)
  57. parsing_function = False
  58. current_func = ""
  59. parsing_comment = False
  60. current_comment = ""
  61. for line in input:
  62. # Discard pre-processor directives ^#.*
  63. if line.startswith("#"):
  64. continue
  65. # Discard "extern C" line
  66. match = reg_externC.match(line)
  67. if match:
  68. continue
  69. # Remove one line comment /* ... */
  70. # eg: extern DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open_path(const char *path, int bExclusive /* = false */);
  71. line = reg_comment_remove_content.sub('', line)
  72. # Get the comment block /* ... */ across several lines
  73. match_start = "/*" in line
  74. match_end = "*/" in line
  75. if match_start and match_end:
  76. continue
  77. if match_start:
  78. parsing_comment = True
  79. current_comment = line
  80. continue
  81. if match_end:
  82. parsing_comment = False
  83. current_comment += line
  84. continue
  85. if parsing_comment:
  86. current_comment += line
  87. continue
  88. # Get the function prototype across several lines
  89. if parsing_function:
  90. # Append to the current function
  91. current_func += " "
  92. current_func += line.strip()
  93. else:
  94. # if is contains "extern", start grabbing
  95. if "extern" not in line:
  96. continue
  97. # Start grabbing the new function
  98. current_func = line.strip()
  99. parsing_function = True;
  100. # If it contains ';', then the function is complete
  101. if ";" not in current_func:
  102. continue
  103. # Got function/comment, reset vars
  104. parsing_function = False;
  105. func = current_func
  106. comment = current_comment
  107. current_func = ""
  108. current_comment = ""
  109. # Discard if it doesn't contain 'SDLCALL'
  110. if "SDLCALL" not in func:
  111. if args.debug:
  112. print(" Discard: " + func)
  113. continue
  114. if args.debug:
  115. print(" Raw data: " + func);
  116. # Replace unusual stuff...
  117. func = func.replace("SDL_PRINTF_VARARG_FUNC(1)", "");
  118. func = func.replace("SDL_PRINTF_VARARG_FUNC(2)", "");
  119. func = func.replace("SDL_PRINTF_VARARG_FUNC(3)", "");
  120. func = func.replace("SDL_SCANF_VARARG_FUNC(2)", "");
  121. func = func.replace("__attribute__((analyzer_noreturn))", "");
  122. func = func.replace("SDL_MALLOC", "");
  123. func = func.replace("SDL_ALLOC_SIZE2(1, 2)", "");
  124. func = func.replace("SDL_ALLOC_SIZE(2)", "");
  125. func = re.sub(" SDL_ACQUIRE\(.*\)", "", func);
  126. func = re.sub(" SDL_ACQUIRE_SHARED\(.*\)", "", func);
  127. func = re.sub(" SDL_TRY_ACQUIRE\(.*\)", "", func);
  128. func = re.sub(" SDL_TRY_ACQUIRE_SHARED\(.*\)", "", func);
  129. func = re.sub(" SDL_RELEASE\(.*\)", "", func);
  130. func = re.sub(" SDL_RELEASE_SHARED\(.*\)", "", func);
  131. # Should be a valid function here
  132. match = reg_parsing_function.match(func)
  133. if not match:
  134. print("Cannot parse: "+ func)
  135. exit(-1)
  136. func_ret = match.group(1)
  137. func_name = match.group(2)
  138. func_params = match.group(3)
  139. #
  140. # Parse return value
  141. #
  142. func_ret = func_ret.replace('extern', ' ')
  143. func_ret = func_ret.replace('SDLCALL', ' ')
  144. func_ret = func_ret.replace('DECLSPEC', ' ')
  145. # Remove trailling spaces in front of '*'
  146. tmp = ""
  147. while func_ret != tmp:
  148. tmp = func_ret
  149. func_ret = func_ret.replace(' ', ' ')
  150. func_ret = func_ret.replace(' *', '*')
  151. func_ret = func_ret.strip()
  152. #
  153. # Parse parameters
  154. #
  155. func_params = func_params.strip()
  156. if func_params == "":
  157. func_params = "void"
  158. # Identify each function parameters with type and name
  159. # (eventually there are callbacks of several parameters)
  160. tmp = func_params.split(',')
  161. tmp2 = []
  162. param = ""
  163. for t in tmp:
  164. if param == "":
  165. param = t
  166. else:
  167. param = param + "," + t
  168. # Identify a callback or parameter when there is same count of '(' and ')'
  169. if param.count('(') == param.count(')'):
  170. tmp2.append(param.strip())
  171. param = ""
  172. # Process each parameters, separation name and type
  173. func_param_type = []
  174. func_param_name = []
  175. for t in tmp2:
  176. if t == "void":
  177. func_param_type.append(t)
  178. func_param_name.append("")
  179. continue
  180. if t == "...":
  181. func_param_type.append(t)
  182. func_param_name.append("")
  183. continue
  184. param_name = ""
  185. # parameter is a callback
  186. if '(' in t:
  187. match = reg_parsing_callback.match(t)
  188. if not match:
  189. print("cannot parse callback: " + t);
  190. exit(-1)
  191. a = match.group(1).strip()
  192. b = match.group(2).strip()
  193. c = match.group(3).strip()
  194. try:
  195. (param_type, param_name) = b.rsplit('*', 1)
  196. except:
  197. param_type = t;
  198. param_name = "param_name_not_specified"
  199. # bug rsplit ??
  200. if param_name == "":
  201. param_name = "param_name_not_specified"
  202. # recontruct a callback name for future parsing
  203. func_param_type.append(a + " (" + param_type.strip() + " *REWRITE_NAME)" + c)
  204. func_param_name.append(param_name.strip())
  205. continue
  206. # array like "char *buf[]"
  207. has_array = False
  208. if t.endswith("[]"):
  209. t = t.replace("[]", "")
  210. has_array = True
  211. # pointer
  212. if '*' in t:
  213. try:
  214. (param_type, param_name) = t.rsplit('*', 1)
  215. except:
  216. param_type = t;
  217. param_name = "param_name_not_specified"
  218. # bug rsplit ??
  219. if param_name == "":
  220. param_name = "param_name_not_specified"
  221. val = param_type.strip() + "*REWRITE_NAME"
  222. # Remove trailling spaces in front of '*'
  223. tmp = ""
  224. while val != tmp:
  225. tmp = val
  226. val = val.replace(' ', ' ')
  227. val = val.replace(' *', '*')
  228. # first occurence
  229. val = val.replace('*', ' *', 1)
  230. val = val.strip()
  231. else: # non pointer
  232. # cut-off last word on
  233. try:
  234. (param_type, param_name) = t.rsplit(' ', 1)
  235. except:
  236. param_type = t;
  237. param_name = "param_name_not_specified"
  238. val = param_type.strip() + " REWRITE_NAME"
  239. # set back array
  240. if has_array:
  241. val += "[]"
  242. func_param_type.append(val)
  243. func_param_name.append(param_name.strip())
  244. new_proc = {}
  245. # Return value type
  246. new_proc['retval'] = func_ret
  247. # List of parameters (type + anonymized param name 'REWRITE_NAME')
  248. new_proc['parameter'] = func_param_type
  249. # Real parameter name, or 'param_name_not_specified'
  250. new_proc['parameter_name'] = func_param_name
  251. # Function name
  252. new_proc['name'] = func_name
  253. # Header file
  254. new_proc['header'] = os.path.basename(filename)
  255. # Function comment
  256. new_proc['comment'] = comment
  257. full_API.append(new_proc)
  258. if args.debug:
  259. pprint.pprint(new_proc);
  260. print("\n")
  261. if func_name not in existing_procs:
  262. print("NEW " + func)
  263. add_dyn_api(new_proc)
  264. # For-End line in input
  265. input.close()
  266. # For-End parsing all files of sdl_list_includes
  267. # Dump API into a json file
  268. full_API_json()
  269. # Check commment formating
  270. check_comment();
  271. # Dump API into a json file
  272. def full_API_json():
  273. if args.dump:
  274. filename = 'sdl.json'
  275. with open(filename, 'w') as f:
  276. json.dump(full_API, f, indent=4, sort_keys=True)
  277. print("dump API to '%s'" % filename);
  278. # Dump API into a json file
  279. def check_comment():
  280. if args.check_comment:
  281. print("check comment formating");
  282. # Check \param
  283. for i in full_API:
  284. comment = i['comment']
  285. name = i['name']
  286. retval = i['retval']
  287. header = i['header']
  288. expected = len(i['parameter'])
  289. if expected == 1:
  290. if i['parameter'][0] == 'void':
  291. expected = 0;
  292. count = comment.count("\\param")
  293. if count != expected:
  294. # skip SDL_stdinc.h
  295. if header != 'SDL_stdinc.h':
  296. # Warning missmatch \param and function prototype
  297. print("%s: %s() %d '\\param'' but expected %d" % (header, name, count, expected));
  298. # Check \returns
  299. for i in full_API:
  300. comment = i['comment']
  301. name = i['name']
  302. retval = i['retval']
  303. header = i['header']
  304. expected = 1
  305. if retval == 'void':
  306. expected = 0;
  307. count = comment.count("\\returns")
  308. if count != expected:
  309. # skip SDL_stdinc.h
  310. if header != 'SDL_stdinc.h':
  311. # Warning missmatch \param and function prototype
  312. print("%s: %s() %d '\\returns'' but expected %d" % (header, name, count, expected));
  313. # Check \since
  314. for i in full_API:
  315. comment = i['comment']
  316. name = i['name']
  317. retval = i['retval']
  318. header = i['header']
  319. expected = 1
  320. count = comment.count("\\since")
  321. if count != expected:
  322. # skip SDL_stdinc.h
  323. if header != 'SDL_stdinc.h':
  324. # Warning missmatch \param and function prototype
  325. print("%s: %s() %d '\\since'' but expected %d" % (header, name, count, expected));
  326. # Parse 'sdl_dynapi_procs_h' file to find existing functions
  327. def find_existing_procs():
  328. reg = re.compile('SDL_DYNAPI_PROC\([^,]*,([^,]*),.*\)')
  329. ret = []
  330. input = open(SDL_DYNAPI_PROCS_H)
  331. for line in input:
  332. match = reg.match(line)
  333. if not match:
  334. continue
  335. existing_func = match.group(1)
  336. ret.append(existing_func);
  337. # print(existing_func)
  338. input.close()
  339. return ret
  340. # Get list of SDL headers
  341. def get_header_list():
  342. reg = re.compile('^.*\.h$')
  343. ret = []
  344. tmp = os.listdir(SDL_INCLUDE_DIR)
  345. for f in tmp:
  346. # Only *.h files
  347. match = reg.match(f)
  348. if not match:
  349. if args.debug:
  350. print("Skip %s" % f)
  351. continue
  352. ret.append(SDL_INCLUDE_DIR / f)
  353. return ret
  354. # Write the new API in files: _procs.h _overrivides.h and .sym
  355. def add_dyn_api(proc):
  356. func_name = proc['name']
  357. func_ret = proc['retval']
  358. func_argtype = proc['parameter']
  359. # File: SDL_dynapi_procs.h
  360. #
  361. # Add at last
  362. # SDL_DYNAPI_PROC(SDL_EGLConfig,SDL_EGL_GetCurrentEGLConfig,(void),(),return)
  363. f = open(SDL_DYNAPI_PROCS_H, "a")
  364. dyn_proc = "SDL_DYNAPI_PROC(" + func_ret + "," + func_name + ",("
  365. i = ord('a')
  366. remove_last = False
  367. for argtype in func_argtype:
  368. # Special case, void has no parameter name
  369. if argtype == "void":
  370. dyn_proc += "void"
  371. continue
  372. # Var name: a, b, c, ...
  373. varname = chr(i)
  374. i += 1
  375. tmp = argtype.replace("REWRITE_NAME", varname)
  376. dyn_proc += tmp + ", "
  377. remove_last = True
  378. # remove last 2 char ', '
  379. if remove_last:
  380. dyn_proc = dyn_proc[:-1]
  381. dyn_proc = dyn_proc[:-1]
  382. dyn_proc += "),("
  383. i = ord('a')
  384. remove_last = False
  385. for argtype in func_argtype:
  386. # Special case, void has no parameter name
  387. if argtype == "void":
  388. continue
  389. # Special case, '...' has no parameter name
  390. if argtype == "...":
  391. continue
  392. # Var name: a, b, c, ...
  393. varname = chr(i)
  394. i += 1
  395. dyn_proc += varname + ","
  396. remove_last = True
  397. # remove last char ','
  398. if remove_last:
  399. dyn_proc = dyn_proc[:-1]
  400. dyn_proc += "),"
  401. if func_ret != "void":
  402. dyn_proc += "return"
  403. dyn_proc += ")"
  404. f.write(dyn_proc + "\n")
  405. f.close()
  406. # File: SDL_dynapi_overrides.h
  407. #
  408. # Add at last
  409. # "#define SDL_DelayNS SDL_DelayNS_REAL
  410. f = open(SDL_DYNAPI_OVERRIDES_H, "a")
  411. f.write("#define " + func_name + " " + func_name + "_REAL\n")
  412. f.close()
  413. # File: SDL_dynapi.sym
  414. #
  415. # Add before "extra symbols go here" line
  416. input = open(SDL_DYNAPI_SYM)
  417. new_input = []
  418. for line in input:
  419. if "extra symbols go here" in line:
  420. new_input.append(" " + func_name + ";\n")
  421. new_input.append(line)
  422. input.close()
  423. f = open(SDL_DYNAPI_SYM, 'w')
  424. for line in new_input:
  425. f.write(line)
  426. f.close()
  427. if __name__ == '__main__':
  428. parser = argparse.ArgumentParser()
  429. parser.add_argument('--dump', help='output all SDL API into a .json file', action='store_true')
  430. parser.add_argument('--check-comment', help='check comment formating', action='store_true')
  431. parser.add_argument('--debug', help='add debug traces', action='store_true')
  432. args = parser.parse_args()
  433. try:
  434. main()
  435. except Exception as e:
  436. print(e)
  437. exit(-1)
  438. print("done!")
  439. exit(0)